Xeenych Xeenych
Xeenych Xeenych

Reputation: 195

Does malloc and new know about each other?

Assume I have 10 kB heap and mix C and C++ code like that.

char* block1 = malloc(5*1024); //allocate 5
char* block2 = new[](4*1024); // allocate 4

Is there C heap and C++ heap or just a single heap common for both? So that "new" knows that the first 5 kb of heap are already allocated?

Upvotes: 4

Views: 371

Answers (3)

theWiseBro
theWiseBro

Reputation: 1529

An efficient implementation should rather be using system calls brk()/mmap() directly rather than going via malloc(). Though looking at gnu implementation, that isn't the case. It's using malloc() internally.

Upvotes: 0

michi7x7
michi7x7

Reputation: 143

The way that memory allocation works, is that the userspace program first requests one or several memory pages from the operating systems by means of a syscall (sbrk or mmap on *nix). This is usually done by the malloc-implementation (there are several) that is included in your "C-library". This malloc-implementation then manages all pages that it (successfully) requested. This is done in userspace.

Returning to your question: Most implementations of ::operator new will just relay to malloc. But you can always use a different allocator-implementation and even mix several in your program (see: memory pools).*

This is the reason why the standard requires you to not mix malloc/free and new/delete.

*) Many malloc-implementations have problems with lots of small objects (which is pretty common in C++), this is a good reason for changing the allocator.

Upvotes: 0

Pete Becker
Pete Becker

Reputation: 76305

There may or may not be separate C and C++ heaps. You can't write a conforming C++ program that can tell the difference, so it's entirely up to the implementation.

The standard describes the first step in the default behavior of operator new like this:

Executes a loop: Within the loop, the function first attempts to allocate the requested storage. Whether the attempt involves a call to the C standard library functions malloc or aligned_alloc is unspecified. [new.delete.single]/4.1.

And for malloc itself, the standard says: "[aligned_alloc, calloc, malloc, and realloc] do not attempt to allocate storage by calling ::operator new()" [c.malloc]/3.

So the intention is that it's okay to call malloc from operator new, but it's not required.

In practice, operator new calls malloc.

Upvotes: 8

Related Questions