Is reusing a memory location safe?

It’s “OK”, it works as you have written it (assuming primitives and plain-old-datatypes (PODs)). It is safe. It is effectively a custom memory manager.

Some notes:

  • If objects with non-trivial destructors are created in the location of the allocated memory, make sure it is called

    obj->~obj();
    
  • If creating objects, consider the placement new syntax over a plain cast (works with PODs as well)

    Object* obj = new (data) Object();
    
  • Check for a nullptr (or NULL), if malloc fails, NULL is returned

  • Alignment shouldn’t a problem, but always be aware of it when creating a memory manager and make sure that the alignment is appropriate

Given you are using a C++ compiler, unless you want to keep the “C” nature to the code you can also look to the global operator new().

And as always, once done don’t forget the free() (or delete if using new)


You mention that you are not going to convert any of the code just yet; but if or when you do consider it, there are a few idiomatic features in C++ you may wish to use over the malloc or even the global ::operator new.

You should look to the smart pointer std::unique_ptr<> or std::shared_ptr<> and allow them to take care of the memory management issues.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)