c - GCC 提示 str 不能为 NULL

标签 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,对吧?

最佳答案

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

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

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

关于c - GCC 提示 str 不能为 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46156677/

相关文章:

c - 我在关于基本对话的数组中遇到了麻烦

C++ 数组和指针

C++ 可变长度数组 (VLA) 警告

c++ - 持有派生类引用的基类的 std::unique_ptr 在 gcc 编译器中不显示警告,而裸指针显示它。为什么?

c - 为什么使用gcc返回局部变量地址时得不到警告信息?

c - 将内存分配给字符串双指针数组?

c - 通过 scanf 检测数据类型 + 在其他函数中使用它

c - 使用命令行参数执行位于内存中的程序

对使用 gcc 收到的编译器错误感到困惑

C:为什么为 int 参数传递 float/double 文字不会引发警告?