[問題] 多了printf 之後 結果不一樣

看板C_and_CPP作者 (JoJo)時間9年前 (2015/06/08 14:43), 編輯推噓0(007)
留言7則, 5人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): #include <iostream> #include <stdio.h> #include <stdlib.h> int *pcell_sig; int main() { int a = 5; int b=4; int c=3; //printf("%p\n",&a); //printf("%p\n",&b); //printf("%p\n",&c); pcell_sig = (int *)new int[3]; pcell_sig=&a; pcell_sig[1]=b; pcell_sig[2]=c; printf("%d\n",*pcell_sig); printf("%d\n",pcell_sig[1]); printf("%d\n",pcell_sig[2]); return 0; } 把中間那三行printf mark掉之後 printf出來的結果是5 4 4 但是如果沒有mark掉 printf出來的結果是 5 4 3 請問各位大大 哪裡有bug? 餵入的資料(Input): 預期的正確結果(Expected Output): 錯誤結果(Wrong Output): 程式碼(Code):(請善用置底文網頁, 記得排版) 補充說明(Supplement): -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 122.146.84.72 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1433745794.A.B24.html

06/08 14:45, , 1F
pcell_sig=&a; <= 這行你知道在寫啥嗎?
06/08 14:45, 1F

06/08 15:03, , 2F
雖然系統有回收機制但是用new最好再加上delete
06/08 15:03, 2F

06/08 15:32, , 3F
這種加個printf執行就不一樣的 99%都是未定義行為
06/08 15:32, 3F

06/08 15:33, , 4F
例如這篇未定義行為就出在pcell_sig=&a之後幾行
06/08 15:33, 4F

06/08 16:25, , 5F
加上volatile int你就會看到有無printf一樣也GG
06/08 16:25, 5F

06/08 16:27, , 6F
可以玩看看, http://goo.gl/MbH5IP, 按Compile再Run。
06/08 16:27, 6F

06/08 19:37, , 7F
感謝各位高手 我了解了
06/08 19:37, 7F
文章代碼(AID): #1LTJc2ia (C_and_CPP)