Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ new operator - memory layout

Tags:

c++

oop

memory

Is the new operator guaranteed to allocate a continuous chunk of heap memory? I.e. is

objects=new Base[1024];

in terms of memory allocation the same as

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

or can there be gaps?

like image 953
Mark Avatar asked May 04 '12 08:05

Mark


People also ask

Does the new operator allocate memory?

The new operator denotes a request for memory allocation on the Free Store. If sufficient memory is available, a new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable.

How do I allocate memory in runtime using new operator?

Syntax to use new operator: To allocate memory of any data type, the syntax is: pointer-variable = new data-type; Here, pointer-variable is the pointer of type data-type. Data-type could be any built-in data type including array or any user defined data types including structure and class.

What is the memory layout of C program?

A C program memory layout in C mainly comprises six components these are heap, stack, code segment, command-line arguments, uninitialized and initialized data segments. Each of these segments has its own read, write permissions.

Where does new memory get allocated?

In C, dynamic memory is allocated from the heap using some standard library functions. The two key dynamic memory functions are malloc() and free(). The malloc() function takes a single parameter, which is the size of the requested memory area in bytes. It returns a pointer to the allocated memory.


2 Answers

Yes, the memory will be continuous. In terms of allocation, it's the same as the malloc version, but there are several differences (calls to constructor, new doesn't return NULL, malloc doesn't throw exceptions, etc.`).

Note that you can't mix up new[] with delete or free, you have to use delete[] objects to free the memory.

like image 83
Luchian Grigore Avatar answered Sep 20 '22 23:09

Luchian Grigore


Maybe. The new operator does two things: it calls the operator new function, which will return a contiguous block of memory, adequately aligned for all possible types (except when it doesn't; e.g. a misused placement new); it then calls the constructor of the object, which can do just about anything. Including allocating additional blocks, which will not be contiguous with the first.

like image 33
James Kanze Avatar answered Sep 20 '22 23:09

James Kanze