Search code examples
c++charintegerbitreinterpret-cast

c++ reinterpret_cast char to int* / adjacent bits are repeatedly set as 1100


Why does the second example find 1100 instead of 0000 after storing the address in the int pointer and then reading the adjacent bits?

Example 1:

char c = 'a';
int val = *reinterpret_cast<int*>(&c);

val = 97 or 0110 0001


Example 2:

char c = 'a';
int* iptr = reinterpret_cast<int*>(&c);
int val = *iptr;

val = -858993567 or 1100 1100 | 1100 1100 | 1100 1100 | 0110 0001


Solution

  • Both have undefined behavior, generally already because accessing a char through a int pointer is an aliasing violation.

    Even if that was allowed, the size of int will almost certainly be larger than that of char and trying to read an adjacent byte of a variable clearly causes undefined behavior.

    And even further, the alignment of a char variable is probably not guaranteed to be large enough for an int.

    All in all, it is wrong to expect any particular output from the programs.

    In addition, @user253751 points out that the number pattern (1100) is generated in Visual Studio debug build. In the release build, this pattern is not set.