开发者

Compiler does not warn when dereferencing nullptr

This:

开发者_如何学JAVA
int* p = nullptr;
auto tmp = *p;  

doesn't cause neither gcc 4.6 nor VS2010 sp1 to issue at least a warning. Is there any option in any of those compilers to make them issue a warning in cases like this? I test-compiled in VS with /w4.


It's not illegal, it's just undefined behaviour.

Turning on warnings for this might cause a false sense of security, because often it is not known until runtime if some pointer points to nullptr or to something else. Valgrind can check for these errors (and many more).

Not to mention it would dramatically increase compile times.


In Visual Studio 2010 SP1 (don't know which edition you need), run Code Analysis. I just tried with your exact code, and it shows warning 6011:

warning C6011: NULL-Zeiger "p" wird dereferenziert.: Lines: 138, 139


"Cases like this" are quite obscure, and it would require the compiler to backtrack from every de-reference and see if it can prove that it knows that the pointer has a constant, and invalid, value.

Consider that some other piece of the program could be given a pointer to the pointer (aliasing) and overwrite it in a different code path, or (worse) on a different thread.

It's not easy to detect, and I think the cost in terms of compilation time for real-world programs would make it not worth it, if it even could be implemented with a reasonable amount of effort.


valgrind can point this out. I use it to check for this kind of obscure cases, and invalid reads/writes.


This is runtime error, not compile time error. Compiler can catch such dereferences only in very limited cases where it can be completely sure you about pointer value. There is just no point for added complexity.


That is an undefined behaviour. That means the compiler is not required to issue a warning or error.


Dereferencing a null pointer is undefined behavior. The compiler is allowed to diagnose such cases but is not required to.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜