GCC 抱怨 str 不能为 NULL

GCC complains on str not able to be NULL

我有以下代码:

int atoi(const char * str)
{
    int ret = 0, i;
    if (str) {
            for (i = 0; str[i] != '[=10=]'; 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 吧?

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

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

真正的答案:不要 re-use 来自标准库函数的函数名。