Search code examples
cdynamic-memory-allocation

Hypothetical malloc / free implementation with explicit size parameter to free


Would there be any advantages to a dynamic memory allocation and deallocation API where the deallocation function requires the size?

More to the point, are there any interesting implementations of dynamic memory allocation that are off the table because free does not take the size as an argument?

The malloc and free library functions have an interesting asymmetry. free does not require the size of the free'd thing.

void *malloc(size_t size);

vs

void free(void *ptr);

Which means that a malloc implementation has to store the metadata somewhere so that free can do its job*.

If the API were instead:

void free(void *ptr, size_t size);

could you write an implementation of these functions that's more cache-efficient, uses less memory overall, or has more of some desirable property?

*I don't believe that requiring the size in order to free things would completely eliminate the need for storing metadata of some kind, but it could simplify it considerably.


Solution

  • Would there be any advantages to a dynamic memory allocation and deallocation API where the deallocation function requires the size?

    Yes, the user supplied size could be maybe compared against the system's understanding the the size. Alternativley the system would not need to even keep track of the size.

    Yet there is a downside in the the user would then need to keep track. The underlying allocation system has more access to sizing info and can do so more efficiently and more faithfully than the user.

    ... uses less memory overall, ...

    Not likely as the underlying allocation system can perform efficiency tricks beyond portable C better than the burden placed on the user to do the same.


    The Standard C library design choice was made long ago favoring the underlying system keeping track.


    A typical wrapper can use my_alloc(size) and over-allocate to store meta data and my_free(ptr, size) to do this check.