c - 当 unsigned int 可以保存任何地址时, uintptr_t 和 unsigned int 有什么区别吗?

标签 c pointers language-lawyer

uintptr_t的描述:

The following type designates an unsigned integer type with the property that any valid pointer to void can be converted to this type, then converted back to pointer to void, and the result will compare equal to the original pointer:

uintptr_t

由于任何指针都可以转换为 void 指针,反之亦然:

A pointer to void may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.

任何指针都可以转换为uintptr_t反之亦然,好的。

现在,整数和指针的描述:

[Integer -> Pointer ]

An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation

[Pointer -> Integer ]

Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type.

好的。现在,由于在我的系统的 ABI(ARM 体系结构的过程调用标准)中,无符号 int 和指针具有相同的大小和对齐方式,并且我的系统使用从 0x0 开始的普通 32 位连续值。对于内存地址,似乎是实现定义的转换间隙

Integer -> PointerPointer -> Integer

已经在我的系统中填充了,我可以安全地将指针转换为无符号整数,并且将指针转换为uintptr_t没有区别。并将指针转换为 unsigned int在我的系统中(两者都会产生相同的值)。我的假设正确吗?或者我缺少什么?

最佳答案

即使给定 unsigned int 有足够的位来表示 C 实现中的所有地址,C 标准也不能保证这意味着,给定一个 void * 指针 p,表达式 (void *) (unsigned) p == p 计算结果为 true。由于从 void * 到整数的转换是实现定义的,因此它可能不仅仅将地址重新生成为 无符号 值。它可能包含一些描述地址来源或校验和的位,而无符号可能不足以包含恢复原始值所需的信息。

大多数实现可能只是以明显的方式简单地转换地址,将虚拟内存地址的位重新解释为无符号值,并且不会出现任何问题。然而,这是实现的一个特点;这不是 C 标准的要求。

关于c - 当 unsigned int 可以保存任何地址时, uintptr_t 和 unsigned int 有什么区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58289959/

相关文章:

c - 遍历c中的字符串数组

对 C 中的空零感到困惑

你能解释一下这段代码对我来说是如何工作的吗?

c++ - 双*数组,与双*指针

将指针强制转换为仿函数,然后调用它

在 C 中使用双重引用更改 char 数组

c++ - 更改 MSVC 中可执行文件的启动目录

c++ - C++14 中 main() 的合法定义

c++ - 内联函数体的潜在评估和模板成员的实例化

c++ - GCC 拒绝使用 enum-base 的简单声明; clang 接受它——这是正确的吗?