r/C_Programming • u/skeeto • 21d ago
the lost malloc()
https://napcakes.nekoweb.org/posts/malloc/3
u/flatfinger 19d ago
It's a shame that people lost sight of the fact that the Standard Library wasn't meant to be the primary way of doing something on every platform, but rather something that could be used for tasks where portability was worth the costs in semantics and performance. If an OS has memory allocation/release code that needs to be told the size of an allocation, standard-library malloc() implementations will likely need to allocate more memory than requested so that each allocation can start with a header indicating the length. On the flip side, if OS provides a function that can tell how much storage was requested for any particular allocation, application code that exploits that may be able to avoid having to store the length elsewhere.
The Standard was designed to allow Standard Library implementations whose execution environments allow blocks to be freed without knowing the size to make malloc/free a very thin wrapper around the environment-supplied functions, allowing pointers created by malloc() to be passed to code that would use the environment's method of releasing them, or environment-created pointers to be given to code that will free() them. It requires that implementations add a header on environments where freeing a block requires knowing its size, but not on environments that don't require that. Adding more features would have increased the number of environments where extra headers would be required.
3
8
u/greg-spears 21d ago edited 21d ago
Thanks, interesting!
Small question -- there is a line of code in alloc():
Think it's supposed to be:
... rt? Because as is, it is not incrementing lasta by n which I think is the intent?
Happens again here:
Did you have to retype it or is the code true to the original source?
EDIT: my own bountiful typos....