我有以下代码:
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/