Joe Smith wrote On 05/02/06 17:40,:
"Eric Sosman" ...
But if you've malloced it, isn't the answer to this question sitting in your
source? I don't really get the use of the adverb 'unfortunately' here. Joe
Yes, the program knew the memory size when it called
malloc(). The "unfortunate" thing is that the program quite
often doesn't bother to remember what it once knew, or even
if it remembers it mightn't bother to tell other parts of
the program what it knows.
gets() is, of course, the horrible example. It would
be nice if gets() could somehow discover the size of the
buffer it was given, but a pointer doesn't communicate that
information. Even if it did, the troubles would not be
over; consider
struct {
char buff[100];
int this;
double that;
unsigned int flags;
} *object;
object = malloc(sizeof *object); // assume success
gets (object->buff);
If gets() could query the size of the memory block to which
its argument pointed, it would presumably get the size of
the entire struct rather than just the `buff' element ...
Learning the raw size of a piece of memory may not be useful
unless you also know something about the context.
At the end of the day it's the programmer's job to see
to it that memory blocks are properly sized, and to make the
sizes available where they're needed. C's simplicity incurs
costs; languages with fancier memory management don't so much
eliminate the costs as redistribute them. You pays your money
and you takes your choice.