I have an API in which some functions are declared with the nonnull GCC function attribute, for example:
// declaration in .h
__attribute__((nonnull))
int foo(const char *bar);
[...]
// definition in .c
int foo(const char *bar) {
if (bar == NULL)
return -1;
// do something with bar
...
}
but the NULL check is triggering the -Wnonnull-compare GCC warning. The problem is that the documentation of the nonnull attribute says that it:
causes the compiler to check that, in calls [...], arguments [...] are non-null.
The problem is that it doesn't say anything about runtime. So if I remove this check to please GCC, I may hide, or detect later than necessary, a bug in a calling program.
So should this warning be silenced in this kind of situation? Or is there some kind of error in the documentation making the code without the check, in fact, correct?
FTR, my compiler version is 11.4.0.
Isn't the -Wnonnull-compare warning misleading?
No. There was an error in the GCC 11.4 documentation. It gave an example for the nonnull
attribute in which it said:
For instance, the declaration… causes the compiler to check that, in calls to
my_memcpy
, arguments dest and src are non-null.
However, the non-example descriptive text for the attribute said something different (emphasis added):
It indicates that the referenced arguments must be non-null pointers.
This was corrected in the GCC 12.3 documentation, where the text about the example was changed to:
For instance, the declaration… informs the compiler that, in calls to
my_memcpy
, arguments dest and src are non-null.
while the non-example descriptive text remained the same.
Thus, the nonnull
attribute is an assertion to the compiler that it may assume the pointers are not null, and so the warning that you are comparing a non-null pointer to null is correct.
In conclusion, the nonnull
attribute does not provide the feature that you want of reporting when a null pointer is passed for an argument that should not be null.