Saturday, January 28, 2012

Where memory manger store the size of heap allocation for array

Wondering why you need not to pass the allocated byte size during 'delete' call for an array ?
I was aware that it's stored somewhere behind the pointer but never dig into it. Today i thought to give it a try on my windows m/c (windows XP SP3).

This is the code i wrote :


struct a
{
int m;
float f;
};


void fun(int argc, char** argv)
{
int *i = new int[30];
char *c = new char[15];
a *b = new a[10];
        cout << "fun" << endl;
}

and called function 'fun' from main(). I used WinDbg and step all these allocations and come to 'cout' statement (just a dummy statement, we will not use it). At this point of time, i can see all the local pointer variables and where they point to.

This is what i got.


0:000> dv
           argc = 0n2
           argv = 0x00365df0
              c = 0x00365f70 "???"
              b = 0x00365fc0
              i = 0x00365eb8


So, i got the c, b and i pointer address. I use dd command to dump the memory with offset of 10.


0:000> dd 0x00365f70 - 10
00365f60  0000000f 00000001 00000079 fdfdfdfd
00365f70  cdcdcdcd cdcdcdcd cdcdcdcd fdcdcdcd
00365f80  abfdfdfd abababab feababab feeefeee
00365f90  00000000 00000000 000a0012 001c0706
00365fa0  00365f50 00000000 00000000 00000000
00365fb0  00000050 00000001 0000007a fdfdfdfd
00365fc0  cdcdcdcd cdcdcdcd cdcdcdcd cdcdcdcd
00365fd0  cdcdcdcd cdcdcdcd cdcdcdcd cdcdcdcd

0:000> dd 0x00365fc0 - 10
00365fb0  00000050 00000001 0000007a fdfdfdfd
00365fc0  cdcdcdcd cdcdcdcd cdcdcdcd cdcdcdcd
00365fd0  cdcdcdcd cdcdcdcd cdcdcdcd cdcdcdcd
00365fe0  cdcdcdcd cdcdcdcd cdcdcdcd cdcdcdcd
00365ff0  cdcdcdcd cdcdcdcd cdcdcdcd cdcdcdcd
00366000  cdcdcdcd cdcdcdcd cdcdcdcd cdcdcdcd
00366010  fdfdfdfd abababab abababab feeefeee
00366020  00000000 00000000 001201fb 00ee14ee

0:000> dd 0x00365eb8 - 10
00365ea8  00000078 00000001 00000078 fdfdfdfd
00365eb8  cdcdcdcd cdcdcdcd cdcdcdcd cdcdcdcd
00365ec8  cdcdcdcd cdcdcdcd cdcdcdcd cdcdcdcd
00365ed8  cdcdcdcd cdcdcdcd cdcdcdcd cdcdcdcd
00365ee8  cdcdcdcd cdcdcdcd cdcdcdcd cdcdcdcd
00365ef8  cdcdcdcd cdcdcdcd cdcdcdcd cdcdcdcd
00365f08  cdcdcdcd cdcdcdcd cdcdcdcd cdcdcdcd
00365f18  cdcdcdcd cdcdcdcd cdcdcdcd cdcdcdcd

please note the bold value in hexadecimal. This is same as total bytes allocation requested during 'new' function call. So, this is the location from where 'delete' got the total size allocation value (just 16 bit behind) :).

No comments: