Sign in to follow this  
Triad_prague

Detecting allocated bytes using a void pointer

Recommended Posts

Triad_prague    161
Hello all, I wonder if there's a way to detect the allocated size of the memory thru the usage of void pointer. It's better explained with the source so here it is:

[code]
int main(int argc, char** argv)
{
void* buffer = new char[256];

//can I inspect the memory pointed by 'buffer' and check how many bytes it used)? I know it used 256 bytes but that's cheating. Thanks before

return 0;
}
[/code]

Share this post


Link to post
Share on other sites
SiCrane    11839
There's no portable way to do that. There are various compiler dependent methods of getting at this information. [url=http://www.gamedev.net/topic/144055-what-to-use-in-place-of-sizeof-on-new]This old thread[/url] discusses this a bit.

Share this post


Link to post
Share on other sites
Hodgman    51234
This feature is required by memory allocators, and it's usually achieved through magic/hacks like below:[code]int main(int argc, char** argv)
{
char* buffer;
{
buffer = new char[sizeof(int) + 256];//allocate some extra space
int* size = (int*)buffer;
*size = 256;//write the size at the start of the buffer
buffer = buffer + sizeof(int);//increment the buffer past these extra bytes so the user is unawares that they exist
}

//I can inspect the memory pointed by 'buffer' and check how many bytes it used. I know it used 256 bytes but that's cheating.
int size = *(int*)(buffer - sizeof(int));//size is written directly before the "user allocation"
assert( size == 256 );

delete (buffer - sizeof(int));//this complicates deallocation however...
return 0;
}[/code]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this