Ubica
Ubica

Reputation: 1051

memory structure of a vector<T>

I am playing around with vectors in c++ and I've tried to figure out how a vector looks inside memory...

I made a vector like this: vector<int> numbers = { 1, 2, 3, 4, 5, 6 }; and extracted a couple of information about the vector


&numbers: 002EF8B8

begin()._Ptr: 0031A538

end()._Ptr: 0031A550


data at vector memory location 002EF8B8 :

00 9d 31 00 38 a5 31 00 50 a5 31 00 50 a5 31 00 cc cc cc cc 30 31 82 1f

found begin()._Ptr and end()._Ptr addresses stored there...


and integers found in that address range:

1st int at memory location: 0031A538 = 01 00 00 00

2nd int at memory location: 0031A53C = 02 00 00 00

3rd int at memory location: 0031A540 = 03 00 00 00

4th int at memory location: 0031A544 = 04 00 00 00

5th int at memory location: 0031A548 = 05 00 00 00

6th int at memory location: 0031A54C = 06 00 00 00


Question:

If 002EF8B8 is the memory location of the vector, 31 00 38 a5 and 31 00 50 a5 are beginning and the end of vector, what is 00 9d at the beginning and the data after? 31 00 50 a5 31 00 cc cc cc cc 30 31 82 1f

I got the size with numbers.size()*sizeof(int) but I'm almost sure that's not the actual size of vector in memory.

Can someone explain to me how can I get the size of actual vector, and what does each part of it represent?

something like:

data size [2 bytes] [4 bytes] [4 bytes] [? bytes]

data meaning [something] [begin] [end] [something else]


EDIT: bcrist suggested the use of /d1reportAllClassLayout and it generated this output

1>  class ?$_Vector_val@U?$_Simple_types@H@std@@    size(16):
1>      +---
1>      | +--- (base class _Container_base12)
1>   0  | | _Myproxy
1>      | +---
1>   4  | _Myfirst
1>   8  | _Mylast
1>  12  | _Myend
1>      +---

which is basically [_Myproxy] [_Myfirst] [_Mylast] [_Myend]

Upvotes: 1

Views: 960

Answers (1)

ach
ach

Reputation: 2373

You misinterpret the bytes. On a little-endian machine, the value 0x0031A538 is represented with the sequence of bytes 38 A5 31 00. So, your highlights are shifted.

Actually you have four addresses here: 0x00319D00, 0x0031A538, 0x0031A550 and again 0x0031A550.

A vector minimally needs three values to control its data, one of them being, obviously, the vector base. The other two may be either pointers to the end of vector and the end of allocated area, or sizes.

0x0031A538 is obviously the vector base, 0x0031A550 is both its end and the end of allocated area. What still needs explanation, then, is the value 0x00319D00.

Upvotes: 5

Related Questions