为什么 NULL/0 是对象的非法内存位置?

2022-01-06 00:00:00 null c memory-management c++

我了解 C/C++ 中 NULL 常量的用途,并且我了解它需要在内部以某种方式表示.

I understand the purpose of the NULL constant in C/C++, and I understand that it needs to be represented some way internally.

我的问题是:对于 C/C++ 中的对象来说,0 地址是无效的内存位置是否有一些根本原因?或者我们是否理论上因为这个保留而浪费"了一个字节的内存?

My question is: Is there some fundamental reason why the 0-address would be an invalid memory-location for an object in C/C++? Or are we in theory "wasting" one byte of memory due to this reservation?

推荐答案

空指针实际上不必为 0.在 C 规范中保证,当在指针的上下文中给出常量 0 值时,它是编译器将其视为 null,但是如果您这样做

The null pointer does not actually have to be 0. It's guaranteed in the C spec that when a constant 0 value is given in the context of a pointer it is treated as null by the compiler, however if you do

char *foo = (void *)1;
--foo;
// do something with foo

您将访问 0 地址,不一定是空指针.在大多数情况下,实际情况确实如此,但这不是必需的,因此我们实际上不必浪费那个字节.虽然,在更大的图片中,如果它不是 0,它必须是某个东西,所以一个字节被浪费了某处

You will access the 0-address, not necessarily the null pointer. In most cases this happens to actually be the case, but it's not necessary, so we don't really have to waste that byte. Although, in the larger picture, if it isn't 0, it has to be something, so a byte is being wasted somewhere

由于注释中的混淆,删除了 NULL 的使用.此外,这里的主要信息是空指针!= 0,这里有一些 C/伪代码,显示了我试图提出的观点."请不要实际尝试编译它或担心类型是否正确;意思很明确.

Edited out the use of NULL due to the confusion in the comments. Also, the main message here is "null pointer != 0, and here's some C/pseudo code that shows the point I'm trying to make." Please don't actually try to compile this or worry about whether the types are proper; the meaning is clear.

相关文章