Reputation: 21
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.
Upvotes: 2
Views: 230
Reputation: 2720
ptr
will have indeterminate value before it is assigned some value. And dereferencing a pointer with indeterminate value will invoke undefined behavior
, which can result in anything — including printing a garbage value as seen in your first call to func
, printing 111
as seen in your second call to func
, or even crashing your program.
As a side note, add free(ptr);
at the end of func
so that your program frees memory dynamically allocated with malloc
.
Upvotes: 5
Reputation: 562
Declaring a pointer and dereferncing it before you initialise it is undefined behaviour - it could contain anything. I believe that the reason your pointer prints the same value the second time is because func()
's stack frame is popped after the first call. You then call it again, causing an identical stack frame to be pushed where the first one is. The memory it gave to store the pointer just happened to be the same memory that was allocated to the pointer in the previous call.
Note: You should be freeing the memory that you allocated before exiting the function, or you will have memory leaks.
Upvotes: 1
Reputation: 12272
This is actually envoking undefined behaviour, so nothing can be said for sure. Accessing variables not initialized is undefined behaviour.
That said, It might be that the new frame created is on the same memory.
Upvotes: 1