This is not good luck. You are returning a pointer to a location on the stack. The place is valid, and it has the last meaning that has been put there until something else changes it.
Here is an example, and I borrow an idea from another question that you are linking too, which is exactly the same:
#include <stdio.h> int* foo() { int a = 5; return &a; } void nukestack() { int a = 7; printf("putting 7 on the stack\n"); } void main() { int* p = foo(); printf("%d\n", *p); nukestack(); printf("%d\n", *p); }
Printing from the program will be as follows:
5 putting 7 on the stack 7
The reason is this. First we call foo (), which allocates space on the stack for variable a. We write 5 to this place, then return from the function, freeing this stack space, but leaving the memory intact. Then we call nukestack (), which allocates stack space for its own variable a. Because the functions are so similar and the variables are the same size in both functions, their memory locations happen to overlap.
At this point, the new variable will still have the old value. But we are now rewriting 5 with 7. We are returning from the function, and our old pointer p still points to the same place where there is now 7.
This behavior is undefined, and you technically break the rules if you rely on it. With most compilers, you will also receive a warning when you return a pointer to a local variable, and warnings should never be ignored.
Flawe
source share