Why is NULL/0 an illegal memory location for an object?(为什么 NULL/0 是对象的非法内存位置?)
问题描述
我了解 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.
这篇关于为什么 NULL/0 是对象的非法内存位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 NULL/0 是对象的非法内存位置?
基础教程推荐
- Windows Media Foundation 录制音频 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01