c 指针可以取的值范围? [英] range of values a c pointer can take?

查看:41
本文介绍了c 指针可以取的值范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在计算机系统:程序员的视角",第 2.1 节(第 31 页)中,它说:

In "Computer System: A Programmer's Perspective", section 2.1 (page 31), it says:

C 中指针的值是某个存储块的第一个字节的虚拟地址.

The value of a pointer in C is the virtual address of the first byte of some block of storage.

在我看来,C 指针的值可以从 0 到 [虚拟内存大小 - 1].是这样吗?如果是,我想知道是否有任何机制可以检查程序中的所有指针是否都分配有合法值——值至少为 0,最多为 [虚拟内存大小 - 1],以及这种机制的内置位置——在编译器中?操作系统?或其他地方?

To me it sounds like the C pointer's value can take values from 0 to [size of virtual memory - 1]. Is that the case? If yes, I wonder if there is any mechanism that checks if all pointers in a program are assigned with legal values -- values at least 0 and at most [size of virtual memory - 1], and where such mechanism is built in -- in compiler? OS? or somewhere else?

推荐答案

C 中的指针是一个抽象对象.C 标准提供的唯一保证是,指针可以指向它们在 C 中需要的所有内容:函数、对象、对象末尾的后面和 NULL.

A pointer in C is an abstract object. The only guarantee provided by the C standard is that pointers can point to all the things they need to within C: functions, objects, one past the end of an object, and NULL.

在典型的 C 实现中,指针可以指向虚拟内存中的任何地址,并且一些 C 实现在很大程度上有意支持这一点.但是,也有一些并发症.例如,用于 NULL 的值可能难以用作地址,并且为一种类型创建的指针转换为另一种类型可能会失败(由于对齐问题).此外,还有一些合法的非典型 C 实现,其中指针不以正常方式直接关联到内存地址.

In typical C implementations, pointers can point to any address in virtual memory, and some C implementations deliberately support this in large part. However, there are complications. For example, the value used for NULL may be difficult to use as an address, and converting pointers created for one type to another type may fail (due to alignment problems). Additionally, there are legal non-typical C implementations where pointers do not directly correlate to memory addresses in a normal way.

在不了解 C 标准和您使用的 C 实现的规则的情况下,您不应期望使用指针来任意访问内存.

You should not expect to use pointers to access memory arbitrarily without understanding the rules of the C standard and of the C implementations you use.

C 中没有机制可以检查程序中的指针是否有效.程序员有责任正确使用它们.

There is no mechanism in C which will check if pointers in a program are valid. The programmer is responsible for using them correctly.

这篇关于c 指针可以取的值范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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