Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer from integer without a cast

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.

like image 672
Maestro Avatar asked Jan 30 '13 17:01

Maestro


People also ask

What is pointer without a cast?

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. (

What are the pointers in C language?

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.


2 Answers

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);
like image 151
Michael Burr Avatar answered Oct 20 '22 04:10

Michael Burr


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).

like image 42
Fabien Avatar answered Oct 20 '22 06:10

Fabien