Trishansh Bhardwaj
Trishansh Bhardwaj

Reputation: 518

Is __attribute__((nonnull)) standardized in C

I want to know whether __attribute__((nonnull)) is standard in C or compiler specific. If it's compiler specific then, is there any alternative to do same with standard C?

I am trying to prevent static analyzer's possible null pointer dereference warning, but I don't want to make my code compiler dependent.

Upvotes: 5

Views: 7365

Answers (2)

Mecki
Mecki

Reputation: 133039

__attribute__(...) is never standard C.
No C standard ever defined __attribute__ to even exist.

Upvotes: 5

Petr Skocik
Petr Skocik

Reputation: 60067

It's compiler specific. Neither attributes nor nonnull is mentioned anywhere in the C11 standard.

In C11, you can use the type ParameterName[static 1] syntax, although only clang and zapcc (out of gcc <= 7.1 and clang >= 3.1, zapcc, and icc) generate warnings with it if you pass NULL arguments with it. (Also, it can't be used with void pointers, unfortunately).

__attribute__((__nonnull__)) /*nonstandard*/
void pass_nonnull0(char *X)
{
}

void pass_nonnull1(char X[static 1]) /*standard*/
{ /*the "static 1" means the pointed-to "array" must have at least 1 element*/
}

int main()
{
    pass_nonnull0(0); /* both clang & gcc warn with nonnull attributes */
    pass_nonnull1(0); /* only clang and zapcc warn with type ArgName [static 1] */
}

The semantics of the D[ static type-qualifier-listopt assignment-expression ] syntax don't really guarantee a warning. The syntax only denotes a promise to the compiler that the pointed to object will have at least N elements:

6.7.6.3p7:

A declaration of a parameter as ''array of type'' shall be adjusted to ''qualified pointer to type'', where the type qualifiers (if any) are those specified within the [ and ] of the array type derivation. If the keyword static also appears within the [ and ] of the array type derivation, then for each call to the function, the value of the corresponding actual argument shall provide access to the first element of an array with at least as many elements as specified by the size expression.

However, it is sensible for a compiler to generate a warning if it can see that promise is broken.

Upvotes: 12

Related Questions