C ++ new operator - memory layout

Is the new operator a guarantee to allocate a continuous piece of heap memory? That is it

objects=new Base[1024]; 

in terms of memory allocation just like

 objects=(Base*)malloc(1024*sizeof(base)); 

or can there be spaces?

+6
source share
3 answers

Yes, the memory will be continuous. As for the distribution, it matches the version of malloc , but there are several differences (constructor calls, new do not return NULL , malloc do not throw exceptions, etc.).

Note that you cannot mix new[] with delete or free , you must use delete[] objects to free memory.

+8
source

May be. The new operator performs two functions: it calls the operator new function, which returns a contiguous block of memory adequately aligned for all possible types (except when this is not the case, for example, incorrectly used placement of a new one); it then calls the constructor of the object, which can do anything. Including the allocation of additional blocks that will not be in contact with the first.

+3
source

If the new operator is not overloaded, then the allocated memory block is adjacent. But if it is overloaded, we cannot know (some programmers could overload it: D)

0
source

Source: https://habr.com/ru/post/914876/


All Articles