Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Advanced
Nov 29, 2001

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 bytes
sz= * (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.
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date