Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't there a "memsize" in C which returns the size of a memory block allocated in the heap using malloc?

ok. It can be called anything else as in _msize in Visual Studio.

But why is it not in the standard to return the size of the memory given the memory block alloced using malloc? Since we can not tell how much memory is pointed to by the return pointer following malloc, we could use this "memsize" call to return that information should we need it. "memsize" would be implementation specific as are malloc/free

Just asking as I had to write a wrapper sometime back to store some additional bytes for the size.

like image 929
dubnde Avatar asked Feb 10 '11 16:02

dubnde


2 Answers

Because the C library, including malloc, was designed for minimum overhead. A function like the one you want would require the implementation to record the exact size of the allocation, while implementations may now choose to "round" the size up as they please, to prevent actually reallocating in realloc.

Storing the size requires an extra size_t per allocation, which may be heavy for embedded systems. (And for the PDP-11s and 286s that were still abundant when C89 was written.)

like image 79
Fred Foo Avatar answered Oct 29 '22 06:10

Fred Foo


To turn this around, why should there be? There's plenty of stuff in the Standards already, particularly the C++ standard. What are your use cases?

You ask for an adequately-sized chunk of memory, and you get it (or a null pointer or exception). There may or may not be additional bytes allocated, and some of these may be reserved. This is conceptually simple: you ask for what you want, and you get something you can use.

Why complicate it?

like image 35
David Thornley Avatar answered Oct 29 '22 06:10

David Thornley