Reputation: 9
How is this code working if after the control returns to main() variable i is removed from the stack how the value can still be 5 as i doesn't exist in main() and the variable to which the pointer is pointing to does not exist.
#include<stdio.h>
int* sum() {
int i=5;
int*a=&i;
printf("%d\n",a);
return a;
}
int main() {
int* a=sum();
printf("%d\n",a);
printf("%d",*a);
}
output:
2293252
2293252
5
Upvotes: -1
Views: 59
Reputation: 19864
What you see is undefined behavior.
Returning the address of the local variable from the function lead to undefined behavior.
So the result might not be as expected on all platforms.
int i=5;
is a local variable and you return the address of this variable. Once you exit the function this variable is no more valid so accessing it outside its scope is undefined behavior. The address in which this local variable was stored shouldn't be returned from the function. Alternatively you can do
int* sum()
{
int*a = malloc(sizeof(int));
*a = 5;
printf("%d\n",*a);
return a;
}
PS: printf("%p",(void*)a);
should be used to print the pointers, using wrong format specifier lead to undefined behavior.
Upvotes: 6
Reputation: 2440
After variable removed from stack it's not cleared but it's just free to use by another variables of your program or freed and returned to OS so if you and your OS do not use this space it's contained your previous value. if OS free page contained this address referenced to that address cause segmentation fault. If you use heap in mean time things get more complicated.
Upvotes: 0