C++ – How to Determine if New Memory is Allocated in Physical RAM

c++

new[] gives us consecutive memory.

C++23 draft N4928, chapter 6.7.5.5.2 (2) "Allocation functions", emphasis mine:

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

Does the C++ specification specify whether that block of memory is actually in physical RAM after the allocation, or may it be in virtual RAM only and thus completely or partially paged to disk?

Origin of this question is a discussion in the comments of this question.

Best Answer

C++ does not really deal with physical machines. It targets some abstract machine that just has some sort of uniform memory. For C++ standard, there is no such thing as physical or virtual memory, so it cannot specify either way. So this is the answer to your question as asked.

Now, if you were to ask "will my new[] allocated memory be allocated in physical memory in reality?", the answer would be "it depends on the environment". For example, your C++ program could target some sort of microcontrontroller like ARM Cortex M3, which has no MMU to speak of. In this case, new[] would give you a chunk of contiguous physical memory at the address you are given (and there is no concept of virtual memory there at all, so your question makes no sense in that environment). You could target DOS, in which case you also get a contiguous physical memory at the address you are given (unless your program runs under VDM of some sort, like in Windows, in which case it doesn't get physical memory). You could target some OS that has MMU but no paging or on-demand allocation. In that case, you'll get contiguous virtual memory which is backed by physical memory - but that physical memory might not be contiguous, and you won't know its address. Finally, you could target some "usual" OS environment with MMU and paging, like Linux - in which case you'll get virtual memory which might not be backed by physical memory (in case of Linux which has on-demand paging - you'll definitely not get physical memory for most of that returned block of virtual memory)