- compiler: gcc 3.3 later
If use the
nonnull attribute, can check in compile-time for situations where NULL is passed as a function argument.
However, it only detects when NULL is specified implicitly, and its functionality is limited because it can not detect situations that are implicitly used.
I’ll go into more detail below about that.
This attribute is use with
-Werror=nonnull compile options.
Meaning is lost when use with
In the gcc-3.3 release note, nonnull was first introduced and used in many places, including the kernel and glibc.
|GCC 3.3 Changes|
A new function attribute, nonnull, has been added which allows pointer arguments to functions to be specified as requiring a non-null value. The compiler currently uses this information to issue a warning when it detects a null value passed in such an argument slot.
Details are kindly documented in the gcc documentation.
nonnull (arg-index, …)
The nonnull attribute specifies that some function parameters should be non-null pointers. For instance, the declaration:
If no argument index list is given to the nonnull attribute, all pointer arguments are marked as non-null. To illustrate, the following declaration is equivalent to the previous example:
As this is a simple attribute, it can be easily understood by sample code.
The importants thing is the argument index list is 1-based, rather than 0-based.
Check with code
-> sample source code: nonnull.c
I have specified that
src in my_test_function() should not be NULL.
The compiler kindly warned that we could not use NULL for argnument 1, 2.
Because warning can overlook sometimes, we can print it out as an error to cause a compilation failure.
nonnull attribute does not mean that don’t need to NULL check about the argument inside the my_test_function() function.
This attribute only check the detectable state at compile-time, which also has limited functionality.
-Wnonnull can not detect for the following situations:
If no argument index list is given to the
nonnull attribute, NULL is checked for all arguments.
Although it is limited in functionality, it may be a good attribute to cover the user’s mistakes to some extent because it can be checked at compile-time for situations where NULL is explicitly used.