Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the memory allocated by new operated consecutive?

Tags:

c++

as the title says, I want to know in c++, whether the memory allocated by one new operation is consecutive...

like image 942
iBacchus Avatar asked Nov 28 '22 06:11

iBacchus


2 Answers

BYTE* data = new BYTE[size];

In this code, whatever size is given, the returned memory region is consecutive. If the heap manager can't allocate consecutive memory of size, it's fail. an exception (or NULL in malloc) will be returned.

Programmers will always see the illusion of consecutive (and yes, infinite :-) memory in a process's address space. This is what virtual memory provides to programmers.

Note that programmers (other than a few embedded systems) always see virtual memory. However, virtually consecutive memory could be mapped (in granularity of 'page' size, which is typically 4KB) in physical memory in arbitrary fashion. That mapping, you can't see, and mostly you don't need to understand it (except for very specific page-level optimizations).

What about this?

BYTE* data1 = new BYTE[size1];
BYTE* data2 = new BYTE[size2];

Sure, you can't say the relative address of data1 and data2. It's generally non-deterministic. It depends on heap manager (such as malloc, often new is just wrapped malloc) policies and current heap status when a request was made.

like image 130
minjang Avatar answered Dec 05 '22 09:12

minjang


The memory allocated in your process's address space will be contiguous.

How those bytes are mapped into physical memory is implementation-specific; if you allocate a very large block of memory, it is likely to be mapped to different parts of physical memory.

Edit: Since someone disagrees that the bytes are guaranteed to be contiguous, the standard says (3.7.3.1):

The allocation function attempts to allocate the requested amount of storage. If it is successful, it shall return the address of the start of a block of storage whose length in bytes shall be at least as large as the requested size.

like image 37
James McNellis Avatar answered Dec 05 '22 09:12

James McNellis