2

Does the following program invoke any undefined behavior? In particular, does it break any strict aliasing rules?

void zeroInt(unsigned char *mem) {
    *reinterpret_cast<int *>(mem) = 0;
}

int main() {
    int value;
    zeroInt(reinterpret_cast<unsigned char *>(&value));
    return value;
}

I compiled it with gcc using -O2 -Wstrict-aliasing=3 and it didn't complain, however the gcc docs say that it doesn't catch all cases.

user1000039
  • 785
  • 1
  • 7
  • 19
  • 3
    It looks fine. The various `char` types are allowed to alias other objects. – Kerrek SB Apr 10 '17 at 12:29
  • related/dupe/good read: http://stackoverflow.com/questions/13995748/when-and-how-is-conversion-to-char-pointer-allowed – NathanOliver Apr 10 '17 at 12:31
  • Note that, since the only thing you do with the reinterpreted pointer is to reinterpret back to the original type, you have a lot more guarantees on behavior. –  Apr 10 '17 at 12:34
  • @KerrekSB So am I allowed to cast back from a char type pointer to the original pointer, assuming I know what the original type is? – user1000039 Apr 10 '17 at 12:36
  • 2
    Absolutely no aliasing whatsoever is happening in your code. You are allowed to cast a pointer to a pointer to a character type and back to the original type. This is not aliasing. Aliasing is when you cast a pointer to a pointer of another type *and then dereference that other pointer*. – n. m. could be an AI Apr 10 '17 at 12:37
  • 2
    @user1000039: As n.m. says, you're not aliasing anything. Your only concern is whether `char*` is suitable for round-tripping other object pointers (which it is, cf. [basic.compound]p5). But even aliasing would be OK, i.e. *accessing* the char array elements. – Kerrek SB Apr 10 '17 at 12:40
  • This is not "type punning". Every case of type punning must be somewhat dependent on the representation of values. – curiousguy Apr 11 '17 at 01:24

0 Answers0