4 ms·
>Is it? I thought that char-pointers-into-char-arrays are specifically allowed to alias with whatever type. I think they mean something like this: char stor
by jilller 3y ago
>Is it? I thought that char-pointers-into-char-arrays are specifically allowed to alias with whatever type.
I think they mean something like this:
char storage[1024];
struct pool pool_of_foos = { storage, sizeof(storage) }; // use storage as my memory
struct foo *p = pool_allocate(&pool_of_foos, sizeof(struct foo));
// pool_allocate cannot be implemented in conforming C or C++.
// i.e you cannot place a 'struct foo object' in the memory location containing 'char objects'
How can malloc() work then you might ask? Well it has defined semantics in the standard, so its essentially a magical special exception, you cannot write such a function yourself in standard C, you must use compiler extensions or assembly.
Which is quite insane that it has come to this, I doubt K&R had that as their intention for the language.
- Joker_vD 3y agoAfter a closer re-reading of C's rules on effective type, I think you're actually right, you return pointers-to-structs that point inside a (static or automatic) char array, you have to slice the storage returned from malloc/calloc/realloc. But C++ has std::launder that allows you to do that, see the very last example in [0]: it does placement-new on a char array, then launders the pointer to that array recasted as a pointer-to-struct, and it's supposed to not be UB. [0] https://en.cppreference.com/w/cpp/utility/launder https://en.cppreference.com/w/cpp/utility/launder
- gpderetta 3y agoYou do not need launder for this. Placement new is enough as long as you refer to the newed object via the pointer returned by new. My understanding is that launder exists if you need to recover the pointer to the allocated object directly from the pool pointer. Re C, I'm far from expert, but I think that the issue exists primarily if you try to allocated within an existing named object (like in the parent examu). If you carve out your allocations from a larger chunk of anonymous memory it is supposedly conforming [A lot of "I think", "supposedly"... All object lifetimes and pointer derivation stuff is underspecified in the standards]