Posts

Showing posts with the label memory

What does std::vector look like in memory?

I read that std::vector should be contiguous. My understanding is, that its elements should be stored together, not spread out across the memory. I have simply accepted the fact and used this knowledge when for example using its data() method to get the underlying contiguous piece of memory. However, I came across a situation, where the vector's memory behaves in a strange way: std::vector<int> numbers; std::vector<int*> ptr_numbers; for (int i = 0; i < 8; i++) { numbers.push_back(i); ptr_numbers.push_back(&numbers.back()); } I expected this to give me a vector of some numbers and a vector of pointers to these numbers. However, when listing the contents of the ptr_numbers pointers, there are different and seemingly random numbers, as though I am accessing wrong parts of memory. I have tried to check the contents every step: for (int i = 0; i < 8; i++) { numbers.push_back(i); ptr_numbers.push_back(&numbers.back()); for (auto ptr_number :...