开发者

Should this use of nullptr produce a compiler error?

开发者 https://www.devze.com 2023-02-07 08:15 出处:网络
Is there a good reason why this code compiles without warning (and crashes when run) with Visual C++ 2010:

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?


Should this use of nullptr produce a compiler error?

No.

Dereferencing a null pointer results in undefined behavior, but no diagnostic is required.

Static analysis should conclude that it will crash, right?

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.


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 typechecking analysis 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? .

0

精彩评论

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