*

 #include <stdio.h>


int main( )

{

 int *j ;

 int * fun( ) ;

j = fun( ) ;

printf ( "\n%d", *j ) ;

}

int *fun( )

{int k = 35 ;

return ( &k ) ;

}


: Here we are returning an address of k from fun( ) and collecting it in j. Thus j becomes pointer to k. Then using this pointer we are printing the value of k. This correctly prints out 35. Now try calling any function (even printf( ) ) immediately after the call to fun( ). This time printf( ) prints a garbage value. Why does this happen? In the first case, when the control returned from fun( ) though k went dead it was still left on the stack. We then accessed this value using its address that was collected in j. But when we precede the call to printf( ) by a call to any other function, the stack is now changed, hence we get the garbage value. If we want to get the correct value each time then we must declare k as static. By doing this when the control returns from fun( ), k would not die.

Comments