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.

Share the Post:
data observability

Data Observability Explained

Data is the lifeblood of any successful business, as it is the driving force behind critical decision-making, insight generation, and strategic development. However, due to its intricate nature, ensuring the

Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved