Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 529
Xeenych Xeenych Avatar asked Mar 03 '23 11:03

Xeenych Xeenych


1 Answers

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.

like image 116
Pete Becker Avatar answered Mar 14 '23 22:03

Pete Becker