Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to get size of allocated memory pointed by a pointer?

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
Dear People...
A small problem in C.
I have a pointer to an allocated heap space, I need to know the size of this space.
Usually we can find a header of 4 (or 8) bytes before the actual area that contains this data. However, when linking pthread to the application, this method does not work.
Does anyone know how to find that data??
Thanks...
 
Eberman,

You might like to try the C Programming forum here on tek-tips - we're just simple system administrators here :) Mike
michael.j.lacey@ntlworld.com
Email welcome if you're in a hurry or something -- but post in tek-tips as well please, and I will post my reply here as well.
 
In ANSI C standard you CAN NOT DO THIS.
It is not a standard where and how size of memory chunk a stored. It depends from the implementation of memory allocation procedure. For example in our program we use 3 different memory allocation procedure and they all stored size in different place. It is not even platform or compiler specific it depends from what library of mem. allocator are you using. Yes, generally pointer to allocated memory has a header with an information, but this information can include not only size but type or some other data also size of this header can change. If you in luck try to play with header it can be more then 4 or 8 byte try to find the bytes which store the size. But some allocators do not create header for each pointer they can use some kind of general table or something like that.
But I personally would not advise to use this way, just store the size in some other place or you will potentially have problem with any new upgrade. With C you can do a lot of things, but doing things like that you are digging a grave for your project. Try stick to standard.
Regards.
 
I think that taking a look to the programming manuals for your HP (RTFM always works, isn't it?) might help. If I remember correctly, HP-UX C compiler (if that's the one you're using) has some non standard extensions allowing you to get mor information on the memroy region pointed to by the pointer returned by malloc.
As the prvious post pointed out too, be careful, it is *not* portable, and it will not work on any other U*X box!
Good luck!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top