Hi,
Is it possible to allocate memory using malloc() (C) and release it using delete (C++)
or even the opposite
Alocate with new (C++) and release with free() (C)
If not Why?
Hi,
Is it possible to allocate memory using malloc() (C) and release it using delete (C++)
or even the opposite
Alocate with new (C++) and release with free() (C)
If not Why?
You can't, because new can work very differently from malloc and have its own memory management scheme. You can only pass pointers that were returned by malloc to free - those returned by new probably were never returned by malloc.
Interchanging free/delete and new/malloc might seem to work in some cases, namely when new and delete are implemented in the following "naive" way:
void* operator new(size_t size)
{
return malloc(size);
}
void operator delete(void* p)
{
free(p);
}
But imagine a small-object allocator that say, preallocates chunks of 64k using malloc and then passes out pointers within that block for each call to new. Trying to use free on these pointers would result in disaster.
Not to mention no constructors and destructors are called when using malloc/free.
@OP: There is simply no reason to do this. Why would you want to do this?
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.