Using malloc
and free
, it is easy to allocate structures with extra data beyond the end. But how do I accomplish the same with new
/ delete
?
I know I could use placement new syntax along with malloc
for the allocation part, but will delete
work properly and portably if I place an object in memory allocated by malloc
?
What I want to accomplish is the same as the following example, but using new
/ delete
instead of malloc
/ free
, so that constructors/destructors will be called properly:
#include <cstdlib>
#include <cstring>
#include <iostream>
class Hamburger {
int tastyness;
public:
char *GetMeat();
};
char *Hamburger::GetMeat() {
return reinterpret_cast<char *>(this) + sizeof(Hamburger);
}
int main(int argc, char* argv[])
{
Hamburger* hb;
// Allocate a Hamburger with 4 extra bytes to store a string.
hb = reinterpret_cast<Hamburger*>(malloc(sizeof(Hamburger) + 4));
strcpy(hb->GetMeat(), "yum");
std::cout << "hamburger is " << hb->GetMeat() << std::endl;
free(hb);
}
Output: hamburger is yum