When I call a function that expects a pointer, and I pass in a value, I get this warning, and I like that.
But when the value happens to be a literal '0', I don't get the warning. I think this is because C think it's null-pointer, and not a value. Is there any way to still get warnings for 0-literals, because I already had some bugs because of it.
It means exactly what it says: You are trying to assign an address ( pointer value ) to an integer variable. While this is tecnhically allowed, doing so without explicitly converting the pointer to an int is a sign this is probably not what you were intending , hence the warning. (
The pointer in C language is a variable which stores the address of another variable. This variable can be of type int, char, array, function, or any other pointer. The size of the pointer depends on the architecture. However, in 32-bit architecture the size of a pointer is 2 byte.
GCC supports a nonnull
attribute on function parameters that can do what you want (as long as the -Wnonnull
warning option is enabled):
void* foo( int* cannot_be_null) __attribute((nonnull (1))) ;
int main(int argc, char *argv[])
{
int x;
foo(&x);
foo(0); // line 13 - generates a -Wnonnull warning
return 0;
}
When compiled using gcc -c -Wnonnull test.c
I get:
test.c: In function 'main':
test.c:13:5: warning: null argument where non-null required (argument 1) [-Wnonnull]
You can force this to be an error with -Werror=nonnull
.
Note that this warning is only thrown when the null pointer literal (another name for 0
) is used - the following code doesn't trigger the warning:
int* p = NULL;
foo(p);
Not with a raw C compiler unfortunately. You should try a lint tool, as splint, that might help you about this (I'm not sure, though).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With