Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GCC complains on str not able to be NULL

Tags:

c

gcc-warning

I have the following code:

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;
}

when trying to compile it with

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

I'm using the gcc version:

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

I don't understand the warning. A const char * should be able to be NULL, right?

like image 571
iveqy Avatar asked Sep 11 '17 13:09

iveqy


1 Answers

atoi is a standard function in the c library. The header for that standard function contains the attribute __nonnull, which triggers special gcc handling.

Your overridden implementation doesn't make use of that special handling (honoring the assumption that the argument is not null), thus the warning.

The real answer: don't re-use a function name from a function from the standard library.

like image 156
Peter Avatar answered Oct 05 '22 08:10

Peter