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
aknown by the memory location0xffff0012is set to0x76543210, then they could be laid out in memory as:and you can see that the address of index
nis0x76543210 + 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
mallochousekeeping overhead which, like the pointer itself, is minuscule compared to your actual array.