Skip to content
This repository has been archived by the owner on May 27, 2021. It is now read-only.

vec_-functions induce UB #3

Open
Loli-Ruri opened this issue Dec 3, 2014 · 3 comments
Open

vec_-functions induce UB #3

Loli-Ruri opened this issue Dec 3, 2014 · 3 comments

Comments

@Loli-Ruri
Copy link

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

@oblique
Copy link

oblique commented Dec 22, 2014

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.

@Loli-Ruri
Copy link
Author

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.

@thalesfm
Copy link

thalesfm commented Jun 15, 2017

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!

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants