[问题] 错误处理函式的用法

楼主: 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