Why is there no “memsize” in C that returns the size of the memory block allocated on the heap using malloc?

OK. It can be called something else, as in _ msize in Visual Studio.

But why is it not in the standard to return the memory size if the memory block is allocated using malloc? Since we cannot determine how much memory the return pointer following malloc points to, we could use this memsize call to return this information if necessary. "memsize" will be implementation specific, like malloc / free

Just asking how I had to write a wrapper to save some extra bytes for size.

+5
c memory-management
Feb 10 '11 at 16:37
source share
4 answers

Because the C library, including malloc , was designed for minimal overhead. A function like the one you need will require the implementation to capture the exact size of the selection, while implementations can now choose to “round” the size as needed to prevent the actual reallocation to realloc .

Storing size requires an extra size_t for each layout, which can be difficult for embedded systems. (Both for the PDP-11s and 286s, which were still in abundance when C89 was written.)

+7
Feb 10 '11 at 16:44
source share

To get around this, why should it be? The Standards already have a lot of material, in particular, the C ++ standard. What are your use cases?

You request an adequate memory size, and get it (either a null pointer or an exception). There, additional bytes can be allocated or not, and some of them may be reserved. This is conceptually simple: you ask what you want and get what you can use.

Why complicate this?

+4
Feb 10 2018-11-11T00:
source share

I do not think there is a definite answer. The developers of the standard probably considered this, and weighed the pros and cons. Everything that is included in the standard should be implemented by each implementation, so adding significant loads to it imposes a significant burden on developers. I think they just did not find this feature useful enough to guarantee this.

+2
Feb 10 '11 at 16:45
source share

In C ++, the shell you are talking about is provided by the standard. If you allocate a memory block with std :: vector , you can use the member function vector :: size () to determine the size of the array and use vector :: capacity () to determine the size of the allocation (which may be different).

C, on the other hand, is a low-level language that leaves such problems managed by the developer, because tracking it dynamically (as you suggest) is not strictly necessary and in many cases will be redundant.

+1
Feb 10 '11 at 17:05
source share



All Articles