I understand this of course, but still I'd like to know why a function like
memsize can't be introduced in the std library.
Here are some good reasons:
- There may be extant implementations where the *implementation* does
not, in fact, keep track of the size of the allocated area. The
implementation may be running in a hosted environment which itself
handles allocation, and malloc, calloc, realloc, and free might just
be wrappers. Your "memsize" could require a substantial and
infelicitous change to such an implementation.
- Either memsize must have defined behavior (whether explicit in the
standard or implementation-defined) for arguments which are not
pointers returned by malloc/calloc/realloc, or it must have undefined
behavior for them. The former would require implementations to be
able to identify pointers to allocated memory and distinguish them
from arbitrary values, which is unreasonable. The latter would
introduce a whole new class of nasty bugs. (Essentially these would
be the same bugs that already exist for free and realloc, but the
mooted memsize would be useful in many contexts where those two are
not, so it would likely be used incorrectly far more often.)
- If memsize always returns the requested size, the implementation now
has to keep track of two sizes: requested and actual.
- If memsize always returns the actual size, you've created potential
skew in the program logic. The allocating function may be written to
treat the maximum amount of data in the allocated area as the
requested size, while another function may use memsize (because,
presumably, the use of memsize is to avoid keeping track of the
requested size) and fill the area to its actual size. Return to the
allocating function and you have silent data truncation. It's easy
to see how this might happen, particularly in maintenance.
What it really comes down to for me, though, is that there few good
purposes served by "memsize" - far fewer than many people seem to
think. A program should keep track of the requested sizes of the
areas it allocates, and treat them as being no larger. Some have
suggested that memsize would be useful for a library which wants to
verify that a receiving area is sufficiently large, but that still
would require a valid pointer from the caller - and what if the
caller wants to use an auto or static array, or a pointer into the
middle of an allocated area, as the destination instead?
--
Michael Wojcik (e-mail address removed)
Thanks for your prompt reply and thanks for your invitatin to your
paradise. Based on Buddihism transmigration, I realize you, European,
might be a philanthropist in previous life! -- supplied by Stacy Vickers