#include <iostream>
int Value()
{
int x = 90;//creates a variable x
return x;//returns the value x, into the caller
//x is destroyed because it is out of scope
}
int * ptr()
{
int x = 7;//creates variable x
return &x;//returns a pointer to x
//x gets destroyed because it is out of scope
}
在main函數返回由值,並通過地址
int y = Value();// y = 7
int *py = ptr();
/* *py = 7, not Undefined Behaviour?? */
我創建這個代碼,並在調試程序,我在*我的觀察窗口PY = 7。 我不應該得到一個未定義的行爲,並且程序崩潰,因爲py指向一個現在有垃圾的地址(ptr()中的x超出了作用域)
與UB的問題是,可能性之一是,它似乎* *工作。嘗試改變調用的順序,你很可能在調用「Value」後看到'* py'改變了值。 –
我現在做到了讓我感謝0.這 – Forat
也很編譯器和操作系統相關。這就是未定義行爲的意思,因爲它是實現定義的,而不是保證在每種情況下都一樣。 – ugar