Is calculating address difference undefined behaviour?

匆匆过客 提交于 2020-05-15 02:07:15

问题


Let's say I perform the following:

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

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

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.

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

Discussion arose from comments in: Print stack in C++


回答1:


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

[expr.reinterpret.cast]

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.

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.




回答2:


Converting pointer to integer of sufficient size is well defined, subtracting unsigned integer from another is well defined regardless of their value. There is no undefined behaviour here.

But also, standard doesn't guarantee any particular value for the converted integers, and therefore neither for the result of their subtraction.



来源:https://stackoverflow.com/questions/61757409/is-calculating-address-difference-undefined-behaviour

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!