[問題] release mode下 array奇怪的錯誤

作者: aoc5000 (香蕉)   2017-05-19 15:09:27
開發平台(Platform): (Ex: Win10, Linux, ...)
MAC 64bit
編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出)
Xcode
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
問題(Question):
軟體要release,因此切換到release mode做編輯和執行,
發現有一段程式碼一直錯誤,
將一個array "byte"的資料使用memcpy複製到另一個array "buf",
檢查此buf後發現,資料為0,而導致錯誤
因此用printf將array "byte"的資料輸出到螢幕上,有值而且竟然就好了!
如果byte沒經過printf就一定會出錯(buf資料為0),想不出來是什麼原因
有經過printf後,buf就會有值
餵入的資料(Input):
unsigned int
預期的正確結果(Expected Output):
資料會用memcpy複製到另一個array,裡面應該有值
錯誤結果(Wrong Output):
皆為0
程式碼(Code):(請善用置底文網頁, 記得排版)
unsigned int byte[4]={0};
*(long*)byte = htonl(uptime);
補充說明(Supplement):
作者: littleshan (我要加入劍道社!)   2017-05-19 16:51:00
把陣列轉成另一個型別的指標再賦值是未定義行為byte[4] 應該宣告為 uint32_t,不要亂轉型

Links booklink

Contact Us: admin [ a t ] ucptt.com