I have written this small program and I executed it. But there is something weird happening. When I run the following program, the program prints a random value for *p, and p points to the same place as i but since i is a local variable to the function, *p does not give 20 but a random value. That is totally understandable. But when I uncomment the printf statement in the *fun function, *p surprisingly prints 20. Could anyone tell me why? Thank you so much!
#include <stdio.h>
int *fun() {
int i = 20;
// printf("&i = %u\n",&i);
return (&i);
}
void main() {
int *p;
p=fun();
printf("p = %u\n",p);
printf("*p = %d\n",*p);
}
Don't return the address of a local object. A local object's life-time matches that of the scope in which it was declared. Consider this example:
Pointer A comes into existence. Object B also comes into existence. Pointer A now points to object B. Object B is destroyed, and no longer exists. What does A point to?
Yes, B wouldn't point to anywhere. It will give a segmentation fault. But if I uncomment the following line in the int *fun(), function:
// printf("&i = %u\n",&i);
and run this program, the second print statement in the main function correctly prints the value as 20. Why would it do that when i does not exist anymore?
Why would it do that when i does not exist anymore?
The memory still exists. The value in the memory will be whatever the processor left there last, which could be 20 or could be something else entirely.
It's undefined behaviour. If you really want to know, you could open up the assembly and see what it's doing. Possibly some kind of compiler optimisation; if you don't do anything with i in fun, maybe it doesn't bother creating it at all, but if you print it out, it has to create it, and since nothing else happens in your code, that memory does not get overwritten at any point.