Detecting the Actual Size of a Memory Block Allocated by new

The following trick isn’t portable. Furthermore, even implementations that currently support it do not guarantee to support it in their future releases. Still, it can teach you a few things about the inner-workings of your heap manager.

When allocating arrays dynamically using new, most implementations store the array’s size in a “cookie”?an integer stashed right before the first array element. Thus, to detect the actual size of the array, read the first word (i.e., int) before its first element. For example:

 char * p = new char [9];int sz= * (int*) (p-sizeof(int)); 

The result under C++ Builder is 12. As you can see, the compiler increases the requested block-size adding three padding bytes to it. This is done in order to meet the system’s alignment requirement. That said, you should never rely on this “feature” and write more than 9 bytes of data to the buffer because implementations often write “magic values” to the padding bytes to detect memory overruns. Here’s another example:

 int *p = new int [75]; // requested size is 75 * 4 bytessz= * (int*) ((char *)(p-4)); // sz equals 300

This time, the allocated block’s size is identical to the requested size of 300 bytes because this value divides by 4 without a remainder. In other words, it naturally aligns on a four-byte boundary.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: