3 ms·
I just wanted to convey the idea so I didn't compile or check the code. But now that you bring up UB, I would change the MY_STRUCT_VAR macro as follows: #def
by frankzinger 8y ago
I just wanted to convey the idea so I didn't compile or check the code. But now that you bring up UB, I would change the MY_STRUCT_VAR macro as follows:
#define MY_STRUCT_VAR(name) \
_Alignof(max_align_t) \
unsigned char name##_buf__[MY_STRUCT_MAX_SIZE]; \
struct my_struct* name = (struct my_struct*)name##_buf__
Ie, changed to unsigned char and set the buffer to have the maximum (strictest) alignment. And added the cast.
It's a pretty widely-used technique and I have satisfied myself in the past that it's not UB (ie, by checking the Standard). I am no language lawyer though so don't take my word for it. The heap example, on the other hand, is pretty much identical to what an allocation inside your library would look like so feel free to disregard the stack example if you'd like.
One example of something based on the same principle is the 'sockaddr' structure in the BSD sockets API. See https://en.wikipedia.org/wiki/Type_punning#Sockets_example https://en.wikipedia.org/wiki/Type_punning#Sockets_example.
- frankzinger 8y ago_Alignof(max_align_t) should be _Alignas(max_align_t) or _Alignas(_Alignof(max_align_t))