Are std :: vector elements contiguous in physical memory?

My question is similar to this one , however I am asking for something else.

It is clear that as the array C you can use the address of the first element std::vector . This means that in virtual memory, std::vector elements are contiguous. However, if the physical memory is fragmented, it is possible that std::vector actually split into many parts of the physical memory.

My question is: Are std::vector elements contiguous in physical memory (as well as virtual memory)?

+7
c ++ memory-management memory vector
source share
3 answers

The memory used to store data in the vector must be on adjacent addresses, since these addresses are visible in the code.

Typically, on most modern processors / operating systems, this means that the virtual addresses must be contiguous. If these virtual addresses cross the page boundary, then there is a good chance that the physical addresses will no longer be adjacent.

I must add that this is rarely a serious problem. In many cases, modern systems have at least some support for such fragmented memory usage down to the hardware level. For example, many network and disk controllers include a scatter / collect function, where the OS uses page tables to translate virtual addresses for a buffer to physical addresses, and then passes several physical addresses directly to the controller, which then collects data from these addresses if they are transferred from memory to peripheral or β€œscatter” data to these addresses if they are transferred from the periphery to memory.

+14
source share

No, there is no guarantee that you will be provided with continuous physical memory in an abstract C ++ machine. Abstractions and hardware below malloc may use non-contiguous memory.

Only your target implementation can make such a guarantee, but the language / model does not care. He relies on a system to do his job.

+6
source share

Virtual mapping of physical memory is handled primarily by the processor, but with kernel support. The userland process cannot know what it is: your program, regardless of the programming language, only deals with virtual memory addresses. You cannot count, and there is no way to find out if two adjacent virtual memory addresses that cross the page border are adjacent in physical memory, so there is absolutely no reason to worry about it.

+1
source share

All Articles