Work with char array with stack alignment problems

See: Posting a new problem

A simple question: will the alignment issue fix?

union
{
    char real_array[sizeof(T)*size];
    T    fake_array[size];
};
+3
source share
3 answers

Yes, this should solve the alignment problem. However, there is no need to create an fake_arrayarray. One member of the type is enough T.

This is actually a fairly widely used trick to force alignment of a specific array.

As a pedantic side: anonymous unions exist only in C ++, but not in C.

+6
source

, , , : ", , ". - .

+1

, .

union
{
    char real_array[sizeof(T)*size];
    T    dummy;
};

, ISO , .

: POD-union POD- , POD-union POD-, POD-;

However, as the standard says, you might wonder if there is any loophole leading to Undefined Behavior if you use non-POD classes ... (but I bet it will work with any compiler anyway).

+1
source

Source: https://habr.com/ru/post/1768320/


All Articles