Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

memory overhead of pointers in c/c++

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

like image 797
monkeyking Avatar asked Nov 27 '22 01:11

monkeyking


2 Answers

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.

like image 188
paxdiablo Avatar answered Dec 10 '22 17:12

paxdiablo


No, there is only a single pointer here, not a pointer per entry. Your size estimate is 1000000*2 + 8.

like image 28
Keith Randall Avatar answered Dec 10 '22 15:12

Keith Randall