Hi,

So, recently I learned about the c99 feature to get NULL pointer checks for array function arguments. I have really never seen this feature used in an actual codebase. It's definitely something I wanted on a few occasions.

To be clear, I'm talking about specifically:
void foo(int array[static 1]);

I checked what warnings this produces - gcc by default produces, none, but with -Wall it produces for this code:

int foo(int array[static 1]){ return array[0]; }

int main(void)
{
#define NULL (void*)0
       foo(NULL);
}

bruh.c: In function 'main':
bruh.c:8:9: warning: argument 1 to 'int[static 1]' is null where non-null expected [-Wnonnull]
   8 |         foo(NULL);
     |         ^~~~~~~~~
bruh.c:3:5: note: in a call to function 'foo'
   3 | int foo(int array[static 1]){ return array[0]; }
     |     ^~~
I think this warning is acceptable, but has some scope for improvement.

I checked what clang did instead, and it seemed nicer, for sure.

bruh.c:8:2: warning: null passed to a callee that requires a non-null argument [-Wnonnull]
       foo(NULL);
        ^   ~~~~
bruh.c:3:13: note: callee declares array parameter as static here
int foo(int array[static 1]){ return array[0]; }
            ^    ~~~~~~~~~~
It's pointing me exactly to the parameter with the static directly, so there is no ambiguity

Also, this is a warning enabled by default, no need to pass -Wall.

Is there a reason gcc doesn't enable this by default? To me, it seems like a warning that's desirable always.

You are explicitly agreeing to never call these functions with NULL, any code doing that is surely broken.

There's no way this gives a false positive, ever.

I'm definitely adding this warning to -Werror on all of my future projects, now that I know about it.

One last thing worth mentioning, is that GCC makes a nicer warning than clang when this is done through __attribute__((nonnull))

bruh.c: In function 'main':
bruh.c:8:9: warning: argument 1 null where non-null expected [-Wnonnull]
   8 |         foo(NULL);
     |         ^~~
bruh.c:3:5: note: in a call to function 'foo' declared 'nonnull'
   3 | int foo(int array[1]){ return array[0]; }
     |     ^~~
 It points out specifically that that it is done through the attribute.

I think it would be nice if the attribute could be underlined also, though.

Clang produces:

bruh.c:8:10: warning: null passed to a callee that requires a non-null argument [-Wnonnull]
       foo(NULL);
            ~~~~^
with no mention that the warning is specifically because of the attribute.

I tried looking on the bug tracker and I could find nothing elaborating on this. Maybe I'm not looking hard enough.

I would be happy to open a PR to improve this warning, if there isn't one already.

It seems it might even be trivial enough for me to investigate and tackle myself, in some spare time.

I see very little code using either of these features, so it's definitely not a high priority task regardless.

Reply via email to