[英]Why doesn't “gcc -Wall” warn for “if (ptr < 0)”?
(A long story... you can directly jump to the question at the end...) (说来话长……可以直接跳到最后的问题……)
I need to use realpath(3)
so I wrote a simple example to try it:我需要使用
realpath(3)
所以我写了一个简单的例子来尝试:
$> cat realpath.c
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
int main(int argc, char * argv[])
{
char pathname[PATH_MAX];
if (realpath(argv[1], pathname) < 0) {
perror("realpath");
return 1;
}
printf("%s\n", pathname);
return 0;
}
$> gcc -Wall -o realpath realpath.c
$> ls /xxx
ls: cannot access '/xxx': No such file or directory
$> ./realpath /xxx/foo/bar
/xxx
The result of ./realpath /xxx/foo/bar
surprised me. ./realpath /xxx/foo/bar
让我吃惊。 According to the manual it makes more sense to fail with ENOENT
.根据手册,使用
ENOENT
失败更有意义。 I even referred to the POSIX and found no answer.我什至提到了 POSIX 并没有找到答案。 After quite some time I reread the manual and found
realpath(3)
returns char *
rather than int
.很长一段时间后,我重新阅读了手册,发现
realpath(3)
返回char *
而不是int
。 I was really irritated by gcc
.我真的被
gcc
激怒了。
So why doesn't gcc (even with -Wall
) warn about if (ptr < 0)
?那么为什么gcc (即使使用
-Wall
)不警告if (ptr < 0)
?
gcc -Wall
does not enable all of GCC's warnings! gcc -Wall
并没有启用所有 GCC 的警告! See this question for more information.有关更多信息,请参阅此问题。
In your case, you need to add the -Wextra
flag:在您的情况下,您需要添加
-Wextra
标志:
gcc -Wall -Wextra -o realpath realpath.c
According toGCC's documentation :根据GCC 的文档:
This enables some extra warning flags that are not enabled by
-Wall
.这会启用
-Wall
未启用的一些额外警告标志。The option
-Wextra
also prints warning messages for the following cases:选项
-Wextra
还会在以下情况下打印警告消息:
A pointer is compared against integer zero with <, <=, >, or >=.
使用 <、<=、> 或 >= 将指针与整数零进行比较。
[...]
[...]
So why doesn't gcc (even with
-Wall
) report a warning forif (ptr < 0)
?那么为什么 gcc (即使使用
-Wall
)不报告if (ptr < 0)
的警告?
The name given to the -Wall
flag is actually misleading, since it does not enable all compiler warnings. -Wall
标志的名称实际上具有误导性,因为它不会启用所有编译器警告。
You need to pass -Wextra
.您需要通过
-Wextra
。 This way, you will get the following compiler warning:这样,您将收到以下编译器警告:
warning: ordered comparison of pointer with integer zero [-Wextra]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.