如果* get_ii()返回堆內存,而不是堆棧內存,這個問題是否會被消除?指針電阻
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 }
來源 - http://www.yolinux.com/TUTORIALS/C++MemoryCorruptionAndMemoryLeaks.html
感謝
與返回引用相同的問題,自動對象的生命週期以範圍結束。在大多數情況下,只需返回一個值。(Do * not * pre-optimize and say「哦,但是我會複製一個大對象,所以我不應該那樣做!我會通過引用作爲參數或返回一個指向動態分配值的指針「但是不要。) – GManNickG 2010-08-10 17:51:17