Apr 16, 2025
You can use nonnull
attribute to write safer, clearer, and faster code.
GCC and Clang support the __attribute__((nonnull))
(or [[gnu::nonnull]]
in C++) to mark function pointer arguments as never NULL
. This helps:
NULL
arguments at compile time.__attribute__((nonnull))
: All pointer args must be non-NULL
.__attribute__((nonnull(1, 3)))
: Only specific arguments (1-based indexing).For example:
void f(int *p) __attribute__((nonnull(1)));
f(NULL); // May trigger warning with -Wall
In C++:
[[gnu::nonnull(2)]] void g(int a, int *b);
Note that
-Wall
to enable warnings.nonnull
in declarations, not definitions.NULL
s—runtime checks are still needed.