GCC抱怨str不能为NULL

时间:2017-09-11 13:16:40

标签: c gcc-warning

我有以下代码:

int atoi(const char * str)
{
    int ret = 0, i;
    if (str) {
            for (i = 0; str[i] != '\0'; i++)
                    if (str[i] >= '0' && str[i] <= '9')
                            ret = ret * 10 + str[i] - '0';
    }   
    return ret;
}

尝试使用

进行编译时
fug@fugtop ~/p/book> make
gcc -c -o db.o db.c -Wall -Werror -std=c99 -g -DVERSION=\"v0.4\"  -Wno-
unused-variable -Wno-unused-function
gcc -c -o misc.o misc.c -Wall -Werror -std=c99 -g -DVERSION=\"v0.4\"  -
Wno-unused-variable -Wno-unused-function
misc.c: In function ‘atoi’:
misc.c:55:5: error: nonnull argument ‘str’ compared to NULL [-Werror=nonnull-compare]
  if (str) {
     ^
cc1: all warnings being treated as errors
Makefile:54: recipe for target 'misc.o' failed
make: *** [misc.o] Error 1

我正在使用gcc版本:

fug@fugtop ~/p/book> gcc --version
gcc (Debian 6.3.0-18) 6.3.0 20170516

我不明白这个警告。 const char *应该可以为NULL,对吧?

1 个答案:

答案 0 :(得分:17)

atoi是c库中的标准函数。该标准函数的标头包含属性__nonnull,它触发特殊的gcc处理。

您重写的实现不会使用该特殊处理(尊重参数不为空的假设),因此警告。

真正的答案:不要重复使用标准库中函数的函数名称。