计算地址差是否不确定行为? [英] Is calculating address difference undefined behaviour?

查看:59
本文介绍了计算地址差是否不确定行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我执行以下操作:

void g(int* x)
{
    int y = 0;
    auto diff = uintptr_t(&y) - uintptr_t(x);
}

void f()
{
    int x = 0;
    g(&x);
}

diff 具有未定义的值,还是代码调用未定义的行为?根据规范,代码是否可以保证正常运行并为 diff 计算一个值,可能没有意义,还是调用UB?我相信有些不相关的变量,但无法查明。

Does diff merely have undefined value, or does the code invoke undefined behaviour? According to the specification, is the code guaranteed to run nicely and compute a value for diff, possibly meaningless, or does it invoke UB? I believe there's something about unrelated variables, but could not pinpoint it.

我对自(包括)C ++ 11以来的任何标准的答案都很感兴趣。

I'm interested in answers regarding any standard since (including) C++ 11.

评论引起了讨论在:使用C ++打印堆栈

推荐答案

引用C ++ 11标准草案。关于将指针转换为整数的主题

To quote the C++11 standard draft. On the subject of converting a pointer to an integer


[expr.reinterpret.cast]

5 可以将整数类型或枚举类型的值显式地将
转换为指针。指针转换为足够大小的
整数(如果实现中存在此类指针),然后又转换回
,则相同的指针类型将具有其原始值;

5 A value of integral type or enumeration type can be explicitly converted to a pointer. A pointer converted to an integer of sufficient size (if any such exists on the implementation) and back to the same pointer type will have its original value; mappings between pointers and integers are otherwise implementation-defined.

由于 uintptr_t 指针与整数之间的映射是实现定义的。必须定义$ c>才能编译代码,然后目标计算机上存在一个整数类型,该类型可以作为指针到整数的转换的目标。映射是由实现定义的,但最重要的是结果不是不确定的。这意味着您将获得两次转换的有效整数。

Since uintptr_t must be defined for the your code to compile, then there exists an integer type on the target machine capable of being the target of the pointer-to-integer conversion. The mapping is implementation defined, but most importantly the result is not indeterminate. This means you obtain some valid integer for both conversions.

因此,减法不是未定义的行为。但是结果是实现已定义。

So the subtraction is not undefined behavior. But the result is implementation defined.

这篇关于计算地址差是否不确定行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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