Assume I have the following code:
Object* obj = new Object();
void* mem = malloc(sizeof(obj) + 40);
*((Object*)mem) = *obj;
In that case, is it guaranteed that obj data would be stored at the beginning of the malloced memory, and can I use the rest of the block mem + sizeof(obj) without overriding obj?
Objectyou are assigning to is a valid Object (i.e. one that was already constructed and in a valid state), but you are using a pointer (mem) to a bunch of uninitialized bytes instead. You might have better luck using placement-new, e.g.Object * newObj = new (mem) Object();