I have heard about the following scenario right when I started programming in C.
"Trying to access from outside, a functions local variable will result in error (or garbage value). Since the stack gets cleared off when we return from the function"
But my below code sample prints a value of 50. I am compiling the code with latest GCC compiler.
#include <stdio.h>
int * left();
int main()
{
int *p=left();
printf("%d\n",*p);
return 0;
}
int * left()
{
int i=50;
return &i;
}
Enlight me on this issue.
Can I know the behaviour in C++ ?? Is it similar to c ..
The behavior according to the C standard is undefined not garbage values. So it's possible, and occasionally likely, that the value will remain unchanged. This is not guaranteed by any means.
This is working by luck / chance / accident and nothing else. Don't rely on this behavior because it will come back to bite you.
As far as the C standard is concerned, the value is undefined.
Practically, as long as nothing is pushed to the stack before the returned value is referenced, it works, but the next time a function is called the return address and new stack frame are pushed to the stack and may overwrite the referenced value.
This would not be considered acceptable coding (because of the undefined nature).