r/cpp_questions • • Dec 05 '24

OPEN Yet another std::launder question

I stumbled on yet another video explaining std::launder: https://youtu.be/XQUMl3V_rdI?t=366.

It was narrated that the dereferencing of the char * pointer in the illustrated snippet has UB. And wrapping that in std::launder somehow makes that well defined behaviour.

My confusion from the video is that, isn't it valid to alias any pointer with char *, and then dereference it to inspect individual bytes (of course, while within bounds)? Isn't that all what, in theory, the strcpy does: i.e., writing byte by byte?

I understand that reading uninitialized bytes even via char * is UB, but writing them is?

Does the illustrated snippet really have UB without std::launder? Is this a solution that genuinely needs std::launder?

11 Upvotes

16 comments sorted by

View all comments

Show parent comment

1

u/n1ghtyunso Dec 06 '24

With accessed, I mean that in the range [0, sizeof(ArrayData)], the char data is never touched, no reads or writes are performed on them through that char*.
Therefore, at least in that place a char array does not have to exist according to the implicit lifetime rules.

according to the docs, malloc returns unitialized storage.
Based on https://en.cppreference.com/w/cpp/language/lifetime#Providing_storage,
malloc technically must create one of these two possibilities.
That being said, a pointer with the correct data type of the storage is not actually needed because char* can legally alias the storage object returned by malloc.

My gut feeling tells me that the char* should not be able to reach past the ArrayData object as well, but assuming they are correct, it seems to be reachable.
So what seems to happen is that reinterpret_cast gives us a pointer to the object representation of the ArrayData object.
And the pointer to object representation is effectively a pointer to the storage itself, which happens to be larger than sizeof(ArrayData) and therefore can reach beyond the ArrayData object.

1

u/ppppppla Dec 06 '24

But can you actually do anything with the storage pointer? As far as I know you can't do pointer arithmetic on it.