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. Maybe more bytes are
allocated than requested, a program shouldn't invoke undefined behaviour
when those extra bytes are overwritten right.
I think a portable function like this could be easily added to C and it
would be used a lot considering how many people have asked for something
like this.
I guess it's not entirely clear if such a function could really be added
that easily. At least it would put another constraint on the implementors
of malloc() and friends which might have been a reason not to introduce
such a function (and many implementations where it's easy to introduce
already have such a function as an extension) - but that's probably better
asked in comp.std.c where the experts for these questions can be found.
I am also not convinced that it would reduce the number of questions
asked - they probably would be immediately replaced by questions like:
"Why does memsize() tell me the block is xyz bytes large when I only
asked for abc bytes?" where abc < xyz. I actually guess that most people
would like to have this functionality to be able to pass pointers to
functions without the need to also pass the size of what's pointed to.
But if that would be possible (by making the memsize() function not
return the real amount of allocated memory but the size requested
in the malloc() call) then this still wouldn't work for fixed sized
arrays - unless some size information is also stored with fixed sized
arrays that can be obtained using the same hypothetical memsize()
fucntion. I.e. it would only really make sense if you could do
void func( int *x );
int main( void ) {
int a[ 100 ], *b = malloc( 250 * sizeof *b );
func( a );
func( b );
return 0;
}
void func( int *x )
{
printf( "%lu\n", ( unsigned long ) ( memsize( x ) / sizeof *x ) );
}
But then the way fixed sized arrays are dealt with would have to be
changed fundamentally...
And, of course, the next logical step would be a malloc() variant with
type information of the allocated memory stored and another function
for determining this type with a "return value" that can be used in
casts or tested for etc., so that void pointers could be passed around
and type-agnostic functions can be written. But then you really would
make C a rather different language...
Regards, Jens