devxlogo

Detecting the Actual Size of a Memory Block Allocated by new

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.

See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist