为什么NULL / 0非法的内存位置,对于一个对象? [英] Why is NULL/0 an illegal memory location for an object?

查看:196
本文介绍了为什么NULL / 0非法的内存位置,对于一个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解的目的 NULL 常数C / C ++,我的理解,它需要重新presented的部分的内部方式

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

我的问题是:是否有一些根本原因的0地址将是一个无效的内存位置的C / C ++对象?还是我们的在理论上浪费的内存一个字节,由于此预订吗?

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值指针的背景下被赋予它被视为由编译器为空,但是如果你做

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 /伪code,显示我试图让的地步。请不要实际尝试编译这个或者担心的类型是否正确;意思很明显。

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非法的内存位置,对于一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆