Jump to content

  • Log In with Google      Sign In   
  • Create Account


Detecting allocated bytes using a void pointer


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
3 replies to this topic

#1 Triad_prague   Members   -  Reputation: 140

Like
0Likes
Like

Posted 30 November 2011 - 06:51 PM

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:

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;
}

the hardest part is the beginning...

Sponsor:

#2 SiCrane   Moderators   -  Reputation: 9387

Like
1Likes
Like

Posted 30 November 2011 - 06:55 PM

There's no portable way to do that. There are various compiler dependent methods of getting at this information. This old thread discusses this a bit.

#3 Hodgman   Moderators   -  Reputation: 27586

Like
1Likes
Like

Posted 30 November 2011 - 07:15 PM

This feature is required by memory allocators, and it's usually achieved through magic/hacks like below:
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;

}


#4 Triad_prague   Members   -  Reputation: 140

Like
1Likes
Like

Posted 30 November 2011 - 10:19 PM

Thx SiCrane, Hodgman....that cleared my doubts. Hmm I guess I'll just keep a list of allocated size rather than complicating myself with those hacks. Once again, thanks!!!:lol:
the hardest part is the beginning...




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS