gcc attribute: nonnull
gcc attribute: nonnull
Reqruies
- Compiler: gcc 3.3 or later
There is a limitation where it cannot detect NULL values determined dynamically at runtime or passed indirectly through variables; we will discuss these constraints in detail later.
If you intentionally use the -Wno-nonnull option, the compiler will not interfere even if the nonnull attribute is applied.
GCC 3.3 Changes
GCC 3.3 ChangesDocC/ObjC/C++ ... 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.
GCC Documentation
gcc/Common-Function-AttributesDocnonnull (arg-index, …) The nonnull attribute specifies that some function parameters should be non-null pointers. For instance, the declaration: extern void * my_memcpy (void *dest, const void *src, size_t len) attribute((nonnull (1, 2))); causes the compiler to check that, in calls to my_memcpy, arguments dest and src are non-null. If the compiler determines that a null pointer is passed in an argument slot marked as non-null, and the -Wnonnull option is enabled, a warning is issued. The compiler may also choose to make optimizations based on the knowledge that certain function arguments will never be null. If no argument index list is given to the nonnull attribute, all pointer arguments are marked as non-null.
Usage
One thing to note is that the argument index list starts from
1 (1-based), not 0.Sample Source Code - nonnull.cc
my_test_function(), it is specified that the dest and src arguments must not be NULL.Build Results
Check Resultbash
Change to error with -Werror=bash
Limitations
As mentioned earlier, this attribute works only in limited situations that are easy to analyze at compile-time (primarily explicit constant inputs).
Situations that cannot be detectedc
a is NULL, but the build succeeds.Check Resultbash
a and passed in the code above, there are cases where the compiler fails to track this immediately due to the situation (e.g., optimization settings), resulting in a successful build without errors.A More Critical Consideration
nonnull attribute will never be NULL.if (dest == NULL) return;) meticulously written inside the function for runtime safety may be regarded as "Dead Code" and completely removed during the compilation process.nonnull attribute is excellent for catching obvious programmer mistakes in external APIs at compile-time, you must realize that it is not a "magic key" that guarantees 100% safety of your internal implementation.Implicitly marking all arguments
Use without argument index listc
Check Result - build failbash
Conclusion
runtime overhead, it is recommended to actively utilize these attributes in the future.