[PATCH] Warn when comparing nonnull arguments to NULL in a function.

Mark Wielaard mjw@redhat.com
Tue Sep 15 08:48:00 GMT 2015


On Mon, 2015-09-14 at 21:37 -0600, Martin Sebor wrote:
> > +void foo(void *bar) __attribute__((nonnull(1)));
> > +
> > +void foo(void *bar) { if (!bar) abort(); } /* { dg-warning "null" "argument ‘bar’ compared to NULL" } */
> 
> This looks like a very useful enhancement. Since the change is limited
> to build_binary_op in the two front ends I wonder if the warning also
> issued for other expressions? For example, suppose I were to add to
> function foo above the following:
> 
>       bool is_null = bar;
> 
> would GCC issue a warning? The same question goes for other expressions
> non-binary expressions, including:
> 
>       bar ? f () : g ();

Yes, it will:

nt.c: In function ‘tf’:
nt.c:9:3: warning: nonnull argument ‘bar’ compared to NULL [-Wnonnull]
   bool is_null = bar;
   ^

nt.c:14:7: warning: nonnull argument ‘bar’ compared to NULL [-Wnonnull]
   bar ? f () : g ();
       ^

> or in C++:
> 
>       bool x = static_cast<bool>(bar);

Likewise for the g++ frontend:

nt.c: In function ‘bool tf(void*)’:
nt.c:12:18: warning: nonnull argument ‘bar’ compared to NULL [-Wnonnull]
   bool is_null = bar;
                  ^
nt.c:14:19: warning: nonnull argument ‘bar’ compared to NULL [-Wnonnull]
   bar ? f () : g ();
                   ^
nt.c:16:33: warning: nonnull argument ‘bar’ compared to NULL [-Wnonnull]
   bool x = static_cast<bool>(bar);
                                 ^

Although I now notice they differ on the placement of the carrot.
Maybe the location passed into the warning is not correct/ideal?

Cheers,

Mark



More information about the Gcc-patches mailing list