Search code examples
cundefined-behavior

is casting char pointer to int pointer a undefined behavior?


In some source I found the following:

uint32_t str_hash = *(*uint32_t)"CM1";

I believe is a undefined behavior because

  1. it cast away const
  2. type punning

Am I wrong? Are there any other violation?


Solution

  • Casting const away is not undefined behavior: only writing to an object that was declared const is undefined behavior.

    Unless your platform's char type is unsigned, then yes, strict aliasing prohibits dereferencing the pointer, and the behavior is undefined. However, in the real world, given most compilers' general leniency towards type punning, and given that the underlying object is const, it is unlikely to cause issues.

    Additionally, in the comments below, davmac raised that "CM1" might not be aligned to a uint32_t's required alignment.

    The safe way to do this would be to use memcpy:

    uint32_t str_hash;
    memcpy(&str_hash, "CM1", sizeof str_hash);
    

    With Clang, this compiles to just one load (which I think is about as good as it can get). There is also no casting away constness, although that wasn't an issue to being with.