我有以下代码:GCC抱怨的STR不能为NULL
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;
}
试图与
[email protected] ~/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版本编译它时:
[email protected] ~/p/book> gcc --version
gcc (Debian 6.3.0-18) 6.3.0 20170516
我不明白这个警告。一个const char *应该能够为NULL,对吗?
与您的问题无关,但您的功能存在严重缺陷...尝试使用例如'“123abc456”作为输入,看看会有什么结果。 –
可能'gcc'试图内联该函数,并知道没有传递给它的NULL参数。这个函数在你的代码中使用了多少次?它的用法是什么? – myaut
似乎是一种误报。虽然'if(str)'与'if(str!= NULL)'相比是马虎的样式,但并不需要为此抛出警告。 – Lundin