0

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?

5
  • 4
    Undefined behaviour is guaranteed. Commented Dec 8, 2019 at 19:49
  • 1
    ok, let's ask the question --what is the real problem you're trying to solve? Commented Dec 8, 2019 at 19:52
  • This won't work, because the assignment operator in the third line expects that the Object you 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(); Commented Dec 8, 2019 at 19:54
  • We were asked to implement malloc and free functions. In order to implement free I need the details about the memory allocated, so my idea was to allocate extra space, so under the user's memory block, I will save a object containing the details about the allocation (size, etc...). Commented Dec 8, 2019 at 19:57
  • What is the right way to it then? Commented Dec 8, 2019 at 19:58

1 Answer 1

4

You're guaranteed to have an undefined behaviour.

First, sizeof(obj) is size of a pointer, not size of Object. Use sizeof(*obj) or sizeof(Object). Second, there is no Object at the location mem, so this dereference *((Object*)mem) is undefined behaviour.

Use placement new:

new (mem) Object(*obj); // or new (mem) Object(std::move(*obj));

to put Object at the beginning of mem block. You can use 40 remaining bytes at your own discretion.

Sign up to request clarification or add additional context in comments.

7 Comments

Better yet, he could use sizeof(Object) and thereby eliminate the Object* obj = new Object(); line entirely.
@JeremyFriesner, it might be the case that obj it somehow modified after first new. If it is not the case, I agree with your comment.
Problem is I can't use malloc or free. could memcpy work?
@GuyBerkovitz Then this seems like a new question to me. Nothing about that was mentioned in this question.
Placement-new will work with any memory, including memory from brk() or mmap().
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.