简体   繁体   中英

Are std::vector elements contiguous in physical memory?

My question is similar to this , however I'm asking something a bit different.

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

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

The memory used to store the data in a vector must be at contiguous addresses as those addresses are visible to the code.

In a typical case on most modern CPUs/OSes, that will mean the virtual addresses must be contiguous. If those virtual addresses cross a page boundary, then there's a good chance that the physical addresses will no longer be contiguous.

I should add that this is only rarely a major concern. Modern systems have at least some support for such fragmented memory usage right down to the hardware level in many cases. For example, many network and disk controllers include "scatter/gather" capability, where the OS uses the page tables to translate the virtual addresses for the buffer to physical addresses, then supplies a number of physical addresses directly to the controller, which then gathers the data from those addresses if it's transferring from memory to peripheral or "scatters" the data out to those addresses if it's transferring from peripheral to memory.

No, there is no guarantee that you will be provided contiguous physical memory in C++'s abstract machine. Abstractions and hardware below malloc are free to use discontiguous memory.

Only your targeted implementation could make such a guarantee, but the language/model does not care. It relies on the system to do its job.

Virtual to physical memory mapping is handled largely by the CPU, but with kernel support. A userland process cannot know what this mapping is: your program, no matter what the programming language, deals solely in virtual memory addresses. You cannot expect, nor is there any way of even finding out, if two adjacent virtual memory addresses that straddle a page boundary are adjacent in physical memory, so there is absolutely no point worrying about it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM