I'm on a 64bit platform, so all memory adrs are 8 bytes.
So to get an estimate of the memory usage of an array, should I add 8 bytes to the sizeof(DATATYPE) for each entry in the array.
Example:
short unsigned int *ary = new short unsigned int[1000000]; //length 1mio
//sizeof(short unsinged int) = 2bytes
//sizeof(short unsinged int*) = 8 bytes
So does each entry take up 10bytes? and will my 1mio length array therefore use atleast 10megabytes?
thanks
No, you don't get a pointer for each and every array index. You get a single pointer pointing to the array, which is a contiguous block of memory, which is why the address of any index can be calculated from the index itself plus the array address.
For example, if the variable a
known by the memory location 0xffff0012
is set to 0x76543210
, then they could be laid out in memory as:
+-------------+ This is on the stack or global.
0xffff0012 | 0x76543210 |
+-------------+
+-------------+ This is on the heap (and may also
0x76543210 | a[ 0] | have some housekeeping information).
+-------------+
0x76543212 | a[ 1] |
+-------------+
0x76543214 | a[ 2] |
+-------------+
0x76543216 | a[ 3] |
+-------------+
: :
+-------------+
0x7672B68E | a[999999] |
+-------------+
and you can see that the address of index n
is 0x76543210 + n * 2
.
So you will actually have one 8-byte pointer and a million 2-byte shorts which, in your case, totals 2,000,008 bytes.
This is on top of any malloc
housekeeping overhead which, like the pointer itself, is minuscule compared to your actual array.
No, there is only a single pointer here, not a pointer per entry. Your size estimate is 1000000*2 + 8.
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