void func(){
int *ptr;
printf("\n *** %d\n",*ptr);
ptr=malloc(sizeof(int));
*ptr=111;
printf("\n ##### %d\n",*ptr);
}
int main()
{
func();
func();
return(0);
}
Output in GCC
*** -1991643855 // Junk value for the first call
##### 111 // After allocating and assigning value
*** 111 // second call pointer the value which 111
##### 111 // second call after assigning
I am confused by the behaviour of malloc in the func(). After the first call, the local variable pointer ptr is cleared in the stack frame. During the second call, ptr is created again in a new stack frame. So the ptr is not pointing to anywhere. So how come when it is printed in the second call, it points to the memory location for 111. It may be very silly. I searched with Google a lot but found no clear answer.