My understanding is that as soon as testStack
is invoked, a new stack frame is created and all local variables will live in that stack frame. And once stack frame is removed those local variable will also be gone.
In below program, I returned that memory location of one of the local variables created in testStack
and I was able to access that variable value again in main
method.
Questions:
- So, this is true that even though stack frame is removed but still that memory location is holding the local variable value or I am misunderstanding something.
- Can it be potentially dangerous that local variables can be accessed like even when its stack frame is removed?
In
testStack
local variablex
was created on stack and its value was also on stack.Would it had made any difference in terms of heap or stack memory if instead of
int x;
I had saidint* x;
string testStack(); int main(void){ string memAdd = testStack(); printf("memAdd = %i\n", memAdd); printf("*memAdd = %i\n", *memAdd); printf("*&memAdd = %i\n", *&memAdd); *&memAdd = 11; printf("*&memAdd = %i\n", *&memAdd); } string testStack(){ int x; printf("%i\n", x); printf("%i %p %p\n", x, x, &x); *&x = 33; printf("%i\n", x); //free(x); return &x; }
O/P:
134513341
134513341 0x80482bd 0xbffd9eac
33
memAdd = -1073897812
*memAdd = 33 //From main method... Stack frame of testStack() should have been removed by now...
*&memAdd = -1073897812
*&memAdd = 11