Mail Archives: djgpp/1995/04/02/20:17:47
>>>>> "DJ" == DJ Delorie <dj AT delorie DOT com> writes:
>> If ASSUMPTION 2 is true, is there an ANSI-C manner to get from
>> the O.S. the amount of memory a pointer points to? I have
>> tried "sizeof(pointer)", but it only returns the size of a
>> single element.
DJ> There is no portable way of doing this. ANSI and POSIX
DJ> specifically stay away from memory allocation techniques. In
DJ> theory, you may be able to reverse-engineer malloc() (or, for
DJ> djgpp, just read the sources) and see how free() figures it
DJ> out, but in general such functionality is not available.
DJ> Given the existence of realloc(), it often does not need to be
DJ> available.
Some people write their own my_malloc/my_realloc/my_free that keep
track of the block size in a portable way and use these routines
consistently. What you do is allocate four bytes more than you need
with `malloc', store the size at the base of the allocated memory, and
then return the allocated address plus four bytes. Your
my_realloc/my_free have to know about this four byte offset, and you
should be careful to handle my_realloc(NULL, size) and my_free(NULL)
correctly.
You can then write a simple function which will tell you the size of a
block allocated by these functions, basically just returning
((long *)p)[-1].
Some programmers also install magic sentinel values before and after
the requested block of memory, which can get checked at various times
(e.g. all calls to my_free and my_realloc) for memory smashage.
-Mat
- Raw text -