vec icon indicating copy to clipboard operation
vec copied to clipboard

vec_-functions induce UB

Open Loli-Ruri opened this issue 10 years ago • 3 comments

#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.

Loli-Ruri avatar Dec 03 '14 11:12 Loli-Ruri

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.

oblique avatar Dec 22 '14 09:12 oblique

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.

Loli-Ruri avatar Mar 28 '15 18:03 Loli-Ruri

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!

thalesfm avatar Jun 15 '17 00:06 thalesfm