[問題] 錯誤處理函式的用法

作者: wtchen (沒有存在感的人)   2015-06-11 17:05:07
開發平台(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語言
作者: Feis (永遠睡不著 @@)   2015-06-11 17:44:00
#include <string.h>
作者: wtchen (沒有存在感的人)   2015-06-11 17:57:00
果然OK了!不過為何可以compile過?感謝
作者: Feis (永遠睡不著 @@)   2015-06-11 18:10:00
It's "C". 你可以不用先宣告. 但預設的 prototype 可能不對印象中 c99 還是 c11 有規定得比較嚴. 我不是很確定一般的函式會有連結錯誤. 可是這例子會自動連結標準函式庫預設的 prototype 跟連結的函式庫不一致造成未定義行為晚點有空我再查查 C99 跟 C11 是不是真的有比較嚴PS: 預設的 prototype 會回傳 int, 但是這裡會轉成 char *直覺是因為 64bit 系統 ?
作者: azureblaze (AzureBlaze)   2015-06-11 18:28:00
我以為用預設prototype gcc會警告?
作者: Feis (永遠睡不著 @@)   2015-06-11 18:36:00
不確定 a 大說的是哪種警告, 但是因為這裡是回傳型態不一樣而已. 所以他的警告就是轉型而已另外一種警告就要開 -Wimplicit-function-declaration
作者: wtchen (沒有存在感的人)   2015-06-11 19:07:00
對,我是用64bit。然後同樣的code (沒有include string.h)我用raspberry pi compile雖然也會有warning卻沒有Segmentation fault不過我還是不懂為何32bit跟64bit會造成這種差別RPI用gcc 4.6.3, lubuntu用gcc 4.9.2
作者: azureblaze (AzureBlaze)   2015-06-11 19:36:00
喔喔int轉ptr預設有開,另外那個要自己開-Wall沒事最好加上去比較安全
作者: suhorng ( )   2015-06-11 19:58:00
LP64: ptr 64-bit, int 32-bit int->pointer 丟失資訊?

Links booklink

Contact Us: admin [ a t ] ucptt.com