What is the meaning of contiguous memory in C++?
What is contiguous memory? Consecutive blocks of memory allocated to user processes are called contiguous memory. For example, if a user process needs some x bytes of contiguous memory, then all the x bytes will reside in one place in the memory that is defined by a range of memory addresses: 0x0000 to 0x00FF.
Contiguous data structure is a method of storing data in contiguous, or adjoining, sectors of memory. When information is written, if there is enough space, the information is written contiguous. However, if there is not enough available space, data is written to multiple places which makes it non-contiguous.
The ContiguousArray type is a specialized array that always stores its elements in a contiguous region of memory. This contrasts with Array , which can store its elements in either a contiguous region of memory or an NSArray instance if its Element type is a class or @objc protocol.
The two important types of contiguous memory management are: Fixed partitioning. Dynamic partitioning.
It means that memory is allocated as a single chunk. This is most often used when talking about containers.
For instance, the vector
and string
classes use a contiguous chunk of memory. This means that if you have a vector that contains the int
elements 123
, 456
, 789
, then you can be assured that if you get the pointer to the first element of the vector, by incrementing this pointer, you'll access the second element (456), and by incrementing it again you'll access the last element (789).
std::vector<int> vec = {123, 456, 789};
int* ptr = &vec[0];
*ptr++ == 123; // is true
*ptr++ == 456; // is true
*ptr++ == 789; // is true
The deque class, on the other hand, does not guarantee contiguous storage. This means that if you have a deque that contains the same elements (123, 456, 789), and that you get a pointer to the first element, you cannot be certain that you'll access the second element by incrementing the pointer, or the third by incrementing it again.
std::deque<int> deque = {123, 456, 789};
int* ptr = &deque[0];
*ptr++ == 132; // true
*ptr++ == 456; // not necessarily true and potentially dangerous
*ptr++ == 789; // not necessarily true and potentially dangerous
Another example of a non-contiguous data structure would be the linked list. With a linked list, it's almost unthinkable that incrementing the head pointer could return the second element.
It is rarely relevant, assuming you use C++ good practices such as using iterators instead of pointers as much as you can, because it lets collections manage how they store their items without having to worry about how they do it. Usually, you'll need memory to be contiguous if you have to call C code from your C++ code, as most C functions were designed to work with contiguous memory because that's the simplest way to do it.
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