2
int a;
auto *pa = reinterpret_cast<unsigned long long*>(&a);
*pa = 10;

int and unsigned long long types have different size. Does this code produce undefined behaviour?

poljak181
  • 585
  • 4
  • 12

1 Answers1

7

Does access to int via pointer to unsigned long long cause UB?

Yes. The behaviour of the program is undefined.

int and unsigned long long types have different size.

The behaviour would be undefined even if the sizes were the same.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • Are you sure, that the behaviour would be undefined even if the sizes were the same? According to this answer https://stackoverflow.com/a/7005988/2008096, as I understand, I can access int value via pointer to unsigned int because of strict aliasing rule. – poljak181 Oct 20 '20 at 19:06
  • 3
    @poljak181 Yes, I am sure. You can access int via pointer to unsigned because those types have exception in the "strict aliasing rule". Sure, they also have the same size but that doesn't mean that the exception applies to all types of same size. – eerorika Oct 20 '20 at 19:10
  • 1
    @poljak181 The exception you speak of only applies for underlying types that are the same but differ on signedness (such as `int` and `unsigned int`, as you mention). The size of the object is unrelated. `sizeof(bool)` may be the same as `sizeof(char)`, but this doesn't mean that the two can be cast between each other -- they have fundamentally different types. Same is true for `sizeof(int)`/`sizeof(long long)`. – Human-Compiler Oct 20 '20 at 19:12
  • 1
    @poljak181: Pointers to signed and unsigned versions of the same named type may be used interchangeably. Because the authors of the Standard didn't explicitly specify that non-obtuse implementations should only treat pointers to integer types whose sizes and representations *could* be different as alias-incompatible if their sizes and/or representations actually *are* different, however, some compiler writers have decided to treat such omission as an invitation to treat such types as incompatible even when their representations are identical. – supercat Oct 20 '20 at 19:13
  • @poljak181: Incidentally, I don't think there is any means by which a program for a platform with 64-bit `long` can determine whether `int64_t` is alias-compatible with `long`, `long long`, or neither, nor whether a program for a platform with 32-bit long could check for compatibility between `int32_t` and `int` or `long`. Since such means would only be needed if a compiler treats matching-representation types as incompatible, and the authors of the Standard never imagined that compilers might do that, the authors of the Standard saw no need to provide such a means. – supercat Oct 21 '20 at 17:58