I wrote a program in C having dangling pointer.
#include
int *func(void)
{
int num;
num = 100;
return #
}
int func1(void
It's because of the way the memory gets allocated.
After calling func
and returning a dangling pointer, the part of the stack where num
was stored still has the value 100
(which is what you are seeing afterwards). We can reach that conclusion based on the observed behavior.
After the change, it looks like what happens is that the func1
call overwrites the memory location that a
points to with the result of the addition inside func1
(the stack space previously used for func
is reused now by func1
), so that's why you see 200.
Of course, all of this is undefined behavior so while this might be a good philosophical question, answering it doesn't really buy you anything.