If *get_ii() returned heap memory, rather than stack memory, would this problem be eliminated?
01 int *get_ii()
02 {
03 int ii; // Local stack variable
04 ii = 2;
05 return ⅈ
06 }
07 main()
08 {
09 int *ii;
10 ii = get_ii(); // After this call the stack is given up by the routine
11 // get_ii() and its values are no longer safe.
12
13 ... Do stuff
14 .. ii may be corrupt by this point.
15 }
Source – http://www.yolinux.com/TUTORIALS/C++MemoryCorruptionAndMemoryLeaks.html
thanks
Yes. Allocating from the heap would work here. Make sure that somewhere you release it again otherwise you’ll leak memory.
Often smart-pointers help with this kind of “don’t forget” logic.