Should I worry about the alignment during pointer casting?

前端 未结 7 1388
遇见更好的自我
遇见更好的自我 2020-11-28 05:47

In my project we have a piece of code like this:

// raw data consists of 4 ints
unsigned char data[16];
int i1, i2, i3, i4;
i1 = *((int*)data);
i2 = *((int*         


        
7条回答
  •  醉话见心
    2020-11-28 06:30

    The correct way to unpack char buffered data is to use memcpy:

    unsigned char data[4 * sizeof(int)];
    int i1, i2, i3, i4;
    memcpy(&i1, data, sizeof(int));
    memcpy(&i2, data + sizeof(int), sizeof(int));
    memcpy(&i3, data + 2 * sizeof(int), sizeof(int));
    memcpy(&i4, data + 3 * sizeof(int), sizeof(int));
    

    Casting violates aliasing, which means that the compiler and optimiser are free to treat the source object as uninitialised.

    Regarding your 3 questions:

    1. No, dereferencing a cast pointer is in general unsafe, because of aliasing and alignment.
    2. No, in C++, C-style casting is defined in terms of reinterpret_cast.
    3. No, C and C++ agree on cast-based aliasing. There is a difference in the treatment of union-based aliasing (C allows it in some cases; C++ does not).

提交回复
热议问题