Is paddings access safe in a structure or pool?

Consider this code. Indentation is guaranteed.

static_assert(_Alignof(char) < _Alignof(double), "Flip!");
static_assert(sizeof(char) < sizeof(double), "Flop!");

struct S {
    char c[1];
    double d;
};
union U {
    char c[1];
    double d;
};

static_assert(sizeof(struct S) == _Alignof(double) * sizeof(double), "Fudge!");
static_assert(sizeof(union U) == sizeof(double), "Futz!");

S s; U u;
s.c[1] = 0; // What?
u.c[1] = 0; // What?

With these static_asserts, he is sure that the overlay will be in the middle or at the end. Is access to them safe?

+4
source share
1 answer

Safe memcpy(), memset()or similar, whole structure, even if it contains padding bits. However, no assumptions can be made regarding the filling preserving its value.

Therefore, the only use when accessing bits of additions is that there is no need to write code to avoid access to it in some situations.

, memcmp(), - , .

0

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


All Articles