determining amoutn of allocated space
Tim McDaniel
mcdaniel at adi.com
Thu Jan 10 02:27:55 AEST 1991
(My apologies if the original version of this article gets out.)
jdb at reef.cis.ufl.edu (Brian K. W. Hook) asks:
> Does anyone know how you can determine the amount of space that a block
> has had allocated for it?
*Dynamically* allocated, I presume?
No, nobody knows. ANSI C has no way, and most implementations provide
no functions or macros. Any implementation has to be able to find
out, but implementations differ, even with the same machine, same
operating system, and/or same compiler.
Your choices, in decreasing order of desirability:
*1* Change the program requirements so you don't have to find it out.
*2* Write wrappers my_malloc() and my_free(), which call malloc() and
free() and also keep track of the sizes elsewhere. Storing the
size in an extra sizeof(double) bytes before the block should work
in practice on most systems. A separate list could be guaranteed
portable.
*3* Get source code for your system, compiler, and standard library,
find out how they do it, and do pointer arithmetic to find the
size. Someday you'll have to port the program to a system
without sources, and you'll be in trouble. Or else they'll change
the system, the compiler, or the library, and your program will
suddenly and mysteriously stop working -- and if you're lucky,
you'll even notice when it breaks.
--
Tim McDaniel Applied Dynamics Int'l.; Ann Arbor, Michigan, USA
Work phone: +1 313 973 1300 Home phone: +1 313 677 4386
Internet: mcdaniel at adi.com UUCP: {uunet,sharkey}!amara!mcdaniel
More information about the Comp.lang.c
mailing list