看板 C_and_CPP 關於我們 聯絡資訊
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) Lubuntu + gcc 問題(Question): 這是我從書上照抄的程式,想練習錯誤處理 不過不知道為何compile後會有warning ferror.c:13:16: warning: initialization makes pointer from integer without a cast char *es = strerror(errno); ^ 還有執行後會有Segmentation fault 餵入的資料(Input): 一個不存在的file nofile.xxx 預期的正確結果(Expected Output): 無Segmentation fault 錯誤結果(Wrong Output): Segmentation fault 程式碼(Code):(請善用置底文網頁, 記得排版) #include <stdio.h> #include <stdlib.h> #include <errno.h> int main(void) { FILE *fp; puts("Open a file nofile.xxx"); fp = fopen("nofile.xxx","r"); if (!fp) { perror("Error!"); } char *es = strerror(errno); puts(es); clearerr(stdin); return 0; } 補充說明(Supplement): 程式出處:邊學邊做C語言 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 90.41.134.196 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1434013509.A.DAA.html
Feis: #include <string.h> 06/11 17:44
wtchen: 果然OK了!不過為何可以compile過? 06/11 17:57
wtchen: 感謝 06/11 17:58
Feis: It's "C". 你可以不用先宣告. 但預設的 prototype 可能不對 06/11 18:10
Feis: 印象中 c99 還是 c11 有規定得比較嚴. 我不是很確定 06/11 18:11
Feis: 一般的函式會有連結錯誤. 可是這例子會自動連結標準函式庫 06/11 18:12
Feis: 預設的 prototype 跟連結的函式庫不一致造成未定義行為 06/11 18:12
Feis: 晚點有空我再查查 C99 跟 C11 是不是真的有比較嚴 06/11 18:13
Feis: PS: 預設的 prototype 會回傳 int, 但是這裡會轉成 char * 06/11 18:17
Feis: 直覺是因為 64bit 系統 ? 06/11 18:17
azureblaze: 我以為用預設prototype gcc會警告? 06/11 18:28
Feis: 不確定 a 大說的是哪種警告, 但是因為這裡是回傳型態不一樣 06/11 18:36
Feis: 而已. 所以他的警告就是轉型而已 06/11 18:36
Feis: 另外一種警告就要開 -Wimplicit-function-declaration 06/11 18:38
wtchen: 對,我是用64bit。然後同樣的code (沒有include string.h) 06/11 19:07
wtchen: 我用raspberry pi compile雖然也會有warning 06/11 19:07
wtchen: 卻沒有Segmentation fault 06/11 19:08
wtchen: 不過我還是不懂為何32bit跟64bit會造成這種差別 06/11 19:09
wtchen: RPI用gcc 4.6.3, lubuntu用gcc 4.9.2 06/11 19:14
azureblaze: 喔喔int轉ptr預設有開,另外那個要自己開 06/11 19:36
azureblaze: -Wall沒事最好加上去比較安全 06/11 19:37
suhorng: LP64: ptr 64-bit, int 32-bit int->pointer 丟失資訊? 06/11 19:58