使用 nullptr 会产生编译器错误吗?
这段代码在使用 Visual C++ 2010 进行编译时没有警告(并且运行时崩溃)是否有充分的理由:
int a = *((int*)nullptr);
静态分析应该断定它将崩溃,对吗?
Is there a good reason why this code compiles without warning (and crashes when run) with Visual C++ 2010:
int a = *((int*)nullptr);
Static analysis should conclude that it will crash, right?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不会。
取消引用空指针会导致未定义的行为,但不需要进行诊断。
可能会。没必要。如果发出警告当然是件好事。专用的静态分析工具(例如 Klocwork)可能会发出警告。
No.
Dereferencing a null pointer results in undefined behavior, but no diagnostic is required.
It might. It doesn't have to. It would certainly be nice if a warning was issued. A dedicated static analysis tool (Klocwork, for example) would probably issue a warning.
是的,静态分析表明它总是会崩溃。但是,这需要编译器实际执行此静态分析。大多数编译器不会这样做(至少我不知道)。
所以问题是:为什么 C/C++ 编译器不做更多的静态类型检查。
编译器不这样做的原因主要是:传统,以及使编译器尽可能简单的哲学。
C(以及较小程度上的 C++)是在计算能力相当昂贵且易于编写编译器非常重要的环境中创建的(因为有许多不同的硬件架构)。
由于静态
类型检查分析会使编译器更难编写,并且编译速度更慢,因此当时并不认为这是一个优先事项。因此大多数编译器没有它。其他语言(例如,Java)做出了不同的权衡,因此在 Java 中,许多在 C 中允许的事情是非法的(例如,无法访问的代码是 Java 中的编译时错误;在 C 中,大多数编译器甚至不会发出警告)。这确实可以归结为哲学。
顺便说一句,请注意,如果您愿意,您可以在 C 中进行静态类型检查 - 有多种工具可用,例如 lint(古老),或参见 有哪些开源 C++ 静态分析工具可用? .
Yes, static analysis would show this to always crash. However, this would require the compiler to actually perform this static analysis. Most compilers do not do this (at least none I know of).
So the question is: Why don't C/C++ compilers do more static type checking.
The reason the compiler does not do this is mostly: tradition, and a philosophy of making the compiler as simple as possible.
C (and to a lesser degree C++) were created in an environment where computing power was fairly expensive, and where ease of writing a compiler was important (because there were many different HW architectures).
Since static
typecheckinganalysis will both make a compiler harder to write, and make it compile more slowly, it was not felt at the time to be a priority. Thus most compilers don't have it.Other languages (e.g.) Java make different tradeoffs, and thus in Java many things are illegal that are allowed in C (e.g. unreachable code is a compile-time error in Java; in C most compilers don't even warn). This really boils down to philosophy.
BTW, note that you can get static typechecking in C if you want it - there are several tools available, e.g. lint (ancient), or see What open source C++ static analysis tools are available? .