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 standard does in fact guarantee that a vector is continuous in memory and that &a [0] can be passed to a C function that expects an array.
Yes, the elements of a std::vector are guaranteed to be contiguous. Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question.
However, the std::vector requirements were such that it was virtually impossible to meet them if the elements were not contiguous. Can somebody clarify this? Show activity on this post. This was missed from C++98 standard proper but later added as part of a TR. The forthcoming C++0x standard will of course contain this as a requirement.
This was missed from C++98 standard proper but later added as part of a TR. The forthcoming C++0x standard will of course contain this as a requirement. 1 A vector is a sequence container that supports random access iterators.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With