简体   繁体   中英

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:

$> 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. According to the manual it makes more sense to fail with ENOENT . I even referred to the POSIX and found no answer. After quite some time I reread the manual and found realpath(3) returns char * rather than int . I was really irritated by gcc .

Question

So why doesn't gcc (even with -Wall ) warn about if (ptr < 0) ?

gcc -Wall does not enable all of GCC's warnings! See this question for more information.

In your case, you need to add the -Wextra flag:

gcc -Wall -Wextra -o realpath realpath.c

According toGCC's documentation :

This enables some extra warning flags that are not enabled by -Wall .

The option -Wextra also prints warning messages for the following cases:

  • A pointer is compared against integer zero with <, <=, >, or >=.

  • [...]

So why doesn't gcc (even with -Wall ) report a warning for if (ptr < 0) ?

The name given to the -Wall flag is actually misleading, since it does not enable all compiler warnings.

You need to pass -Wextra . This way, you will get the following compiler warning:

warning: ordered comparison of pointer with integer zero [-Wextra]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM