从整数指针没有投 [英] 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.
但是,当值恰好是一个字面'0',我没有得到警告。我想这是因为C认为这是空指针,而不是一个值。有什么办法仍然得到0文字警告,因为我已经有了,因为它的一些错误。
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.
推荐答案
GCC支持<一个href=\"http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html#Function-Attributes\"><$c$c>nonnull$c$c>属性上的功能参数可以做你想做的(只要 -Wnonnull
警告选项启用):
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;
}
在使用 GCC -c -Wnonnull test.c以
编译我得到:
test.c: In function 'main':
test.c:13:5: warning: null argument where non-null required (argument 1) [-Wnonnull]
您可以强制这是一个错误 = -Werror非空
。
You can force this to be an error with -Werror=nonnull
.
请注意,这个警告仅仅抛出当空指针文字(别称 0
)用于 - 以下code不会触发报警:
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);
这篇关于从整数指针没有投的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!