0

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?

3
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by firstPerson
0

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.