intmain(void) { int *p = NULL; int i; p = malloc(sizeof(int)); if (p == NULL) return-1; printf("Hello world!\n"); return0; }
这里我的gcc版本比较新,所以和老师的不一致,总之老师的意思就是
不要忽略gcc的警告!!!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# 通过 -Wall 参数让gcc显示全部警告 # 注意'W'要大写 $ gcc hello.c -Wall hello.c: In function ‘main’: hello.c:7:9: warning: implicit declaration of function ‘malloc’ [-Wimplicit-function-declaration] 7 | p = malloc(sizeof(int)); | ^~~~~~ hello.c:2:1: note: include ‘<stdlib.h>’ or provide a declaration of ‘malloc’ 1 | #include <stdio.h> +++ |+#include <stdlib.h> 2 | hello.c:7:9: warning: incompatible implicit declaration of built-in function ‘malloc’ [-Wbuiltin-declaration-mismatch] 7 | p = malloc(sizeof(int)); | ^~~~~~ hello.c:7:9: note: include ‘<stdlib.h>’ or provide a declaration of ‘malloc’ hello.c:6:9: warning: unused variable ‘i’ [-Wunused-variable] 6 | int i; | ^
$ gcc a.c -Wall a.c: In function ‘main’: a.c:12:41: warning: implicit declaration of function ‘strerror’; did you mean ‘perror’? [-Wimplicit-function-declaration] 12 | fprintf(stderr, "fopen():%s\n", strerror(errno)); | ^~~~~~~~ | perror a.c:12:35: warning: format ‘%s’ expects argument of type ‘char *’, but argument 3 has type ‘int’ [-Wformat=] 12 | fprintf(stderr, "fopen():%s\n", strerror(errno)); | ~^ ~~~~~~~~~~~~~~~ | | | | | int | char * | %d