为什么取消引用空指针是未定义的行为?

2021-12-13 00:00:00 pointers c++ undefined-behavior

根据 ISO C++,取消引用空指针是未定义的行为.我的好奇是,为什么?为什么标准决定将其声明为未定义行为?这个决定背后的理由是什么?编译器依赖?似乎没有,因为根据C99标准,据我所知,它是明确定义的.机器依赖?有什么想法吗?

According to ISO C++, dereferencing a null pointer is undefined behaviour. My curiosity is, why? Why standard has decided to declare it undefined behaviour? What is the rationale behind this decision? Compiler dependency? Doesn't seem, because according to C99 standard, as far as I know, it is well defined. Machine dependency? Any ideas?

推荐答案

为取消引用 NULL 指针定义一致的行为将要求编译器在大多数 CPU 架构上的每次取消引用之前检查 NULL 指针.对于专为速度而设计的语言来说,这是一种无法接受的负担.

Defining consistent behavior for dereferencing a NULL pointer would require the compiler to check for NULL pointers before each dereference on most CPU architectures. This is an unacceptable burden for a language that is designed for speed.

它也只修复了一个更大问题的一小部分 - 有很多方法可以使无效指针超出 NULL 指针.

It also only fixes a small part of a larger problem - there are many ways to have an invalid pointer beyond a NULL pointer.

相关文章