Setting a buffer of char* with intermediate casting to int*

前端 未结 6 604
一向
一向 2021-01-11 17:23

I could not fully understand the consequences of what I read here: Casting an int pointer to a char ptr and vice versa

In short, would this work?

set         


        
6条回答
  •  灰色年华
    2021-01-11 18:05

    No, it won't work in every case. Aside from endianness, which may or may not be an issue, you assume that the alignment of uint32_t is 4. But this quantity is implementation-defined (C11 Draft N1570 Section 6.2.8). You can use the _Alignof operator to get the alignment in a portable way.

    Second, the effective type (ibid. Sec. 6.5) of the location pointed to by buffer may not be compatible to uint32_t (e.g. if buffer points to an unsigned char array). In that case you break strict aliasing rules once you try reading through the array itself or through a pointer of different type.

    Assuming that the pointer actually points to an array of unsigned char, the following code will work

    typedef union { unsigned char chr[sizeof(uint32_t)]; uint32_t u32; } conv_t;
    
    void set4Bytes(unsigned char* buffer) {
      const uint32_t MASK = 0xffffffffU;
      if ((uintptr_t)buffer % _Alignof(uint32_t)) {// misaligned
        for (size_t i = 0; i < sizeof(uint32_t); i++) {
          buffer[i] = 0xffU;
        } 
      } else { // correct alignment
        conv_t *cnv = (conv_t *) buffer; 
        cnv->u32 = MASK;
      }
    }
    

提交回复
热议问题