Undefined behavior from pointer math on a C++ array

前端 未结 3 1135
逝去的感伤
逝去的感伤 2021-02-05 06:36

Why the output of this program is 4?

#include 

int main()
{
    short A[] = {1, 2, 3, 4, 5, 6};
    std::cout << *(short*)((c         


        
3条回答
  •  [愿得一人]
    2021-02-05 07:23

    The program has undefined behaviour due to casting an incorrectly aligned pointer to (short*). This breaks the rules in 6.3.2.3 p6 in C11, which is nothing to do with strict aliasing as claimed in other answers:

    A pointer to an object type may be converted to a pointer to a different object type. If the resulting pointer is not correctly aligned for the referenced type, the behavior is undefined.

    In [expr.static.cast] p13 C++ says that converting the unaligned char* to short* gives an unspecified pointer value, which might be an invalid pointer, which can't be dereferenced.

    The correct way to inspect the bytes is through the char* not by casting back to short* and pretending there is a short at an address where a short cannot live.

提交回复
热议问题