vec
vec copied to clipboard
vec_-functions induce UB
#define vec_unpack_(v)\
(char**)&(v)->data, &(v)->length, &(v)->capacity, sizeof(*(v)->data)
Strictly speaking, (char**)&(v)->data
is only correctly defined when data
actually is a char-pointer, elsewise dereferencing this pointer in your functions causes undefined behaviour.
Correct me if I'm wrong, but since data
is already a pointer the &
gives a double pointer, so there is no UB since all pointers have the same alignment.
Having a pointer to a pointer is not the problem. Actually, not even casting it to char **
, but rather dereferencing this casted pointer as it violates strict aliasing rules. Also, architectures exist where pointers to different types have different representations, on such platforms the said code would not work.
A possible fix would be to pass &(v)->data
as a char *
. Since char types are an exception to the strict aliasing rules, one could use this pointer to modify the data
field of the structure without running into UB. Also, as @Loli-Ruri pointed out, it might also be necessary to pass sizeof (v)->data
depending on the architecture. The actual value of the pointer would then need to be memcpy
'ed inside the function using sizeof (v)->data
. That's two birds with one stone!