2013-10-05 63 views
0

執行以下代碼後,q的值是多少? m'從字節2開始存儲在內存中,並且沒有內存問題。整數指針指向未聲明內存的編譯器行爲

int m = 44; 
int* p = &m; 
int n = (*p)++; 
int* q = p - 1; 
++*q; 

當我執行海合會這個代碼,該代碼初始化內存指出,由Q到1606417464,然後最後一行它變爲1606417465.這對我來說很有意義的內存這塊尚未分配一個值。

當我使用xtools在我的mac上執行此代碼時,q指向的內存被初始化爲零,然後在++ * q後更改爲1。任何想法爲什麼發生這種行爲?

+1

那麼,**應該發生什麼? – 2013-10-05 22:18:51

+0

您可能想了解[未定義的行爲和順序點](http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points)。 –

回答

0

當您嘗試修改*q(如++*q)時,您的代碼調用undefined behaviour

int m = 44; // Let's say &m is 1000. 
int* p = &m; // p is 1000 now. 
int n = (*p)++; // assigns 45 to 'n'. 
       // Now *p (which is 'm') becomes 45. 
       // Note p is not modified here but only *p is modified. 
int* q = p - 1; // q is 996 or 1004 (depending on which side stack grows) 
       // and assumes sizeof(int*) == 4 
       // which may or may not a valid address and may not belong 
       // to your program. 
++*q; // Here you are essentially modifying some random memory.