#include<stdio.h>
int *call();
int main()
{
int *ptr;
ptr=call();
fflush(stdin);
printf("%d",*ptr);
return 0;
}
int * call()
{
int x=25;
++x;
return &x;
}
The output for this code is 0. I was expecting 26.
Can someone please explain the reason?
And what should I be doing to get 26?
When you create this function and call it a function frame is pushed into the stack having a space for a int variable declared there. Now you increase the value and try to return address of that. Now function ends and stack frame is deleted. You are trying to read it. It will return something random. Ah not random in its sense but what it returns is not defined. You get 0 ..may get 1 or 23 or 128749 or -7364184 sometimes.
To get 26 you might want to use something from heap.(or declare an array which will be alive long enough). Allocate memory big enough to hold an integer variable. Then manipulate it. Return pointer to that . You will see what you want to see.
Note: It's undefined behavior.... it may return something else when you run at different time or different machine. :)
This heap and stack that I mentioned here are implementation specific. By heap I mean the dynamic memory which we allocate.