Why malloc always does more than I asked for?

https://news.ycombinator.com/rss Hits: 6
Summary

Almost all of us has seen this before when writing a safe c program. we know what this line does, atleast we know the purpose of it,ask for 13 bytes, get 13 bytesthat’s what i thought when i started building this on a friday out of curiosity. 30 mins into it, without writing a single line of code… i knew that this almost never happens.this simple line holds multiple interesting computations and allocations in itself under-the-hood.for example, when I request 13 bytes.actually reserved:+--------+--------------+---------+-------------+ | Header | Back Pointer | Padding | User Memory | +--------+--------------+---------+-------------+ the user memory is the only thing we are gonna use and the *p returns the start of that memory. all the others are just there… not for usage.. why is that??i wondered the same, instead of going into theory.. let’s build a allocator and free.the simplest possible allocatorthe simplest possible allocator doesn’t even have a free(). it’s called a bump allocator - you give it a big chunk of memory upfront (an arena), and every allocation just… moves a pointer forward.typedef struct { uint8_t *cursor; uint8_t *limit; } Arena; cursor is where the next allocation starts. limit is where the arena ends. that’s the whole design.void *bump_alloc(Arena *a, size_t size) { if (a->cursor + size > a->limit) return NULL; // out of memory void *ptr = a->cursor; a->cursor += size; return ptr; } that’s it. you can only ever move forward. it’s the fastest possible allocator. but functionally, useless for anything long-running, because there’s no free(). you can only free the whole arena at once, never a single object inside it.which raises the obvious question: if I can’t free one thing, how do I ever get those 13 bytes back?turns out.. you can’t, not with this design. to get individual free() working, the allocator needs to remember something about every allocation it handed out. and that’s the moment metadata stops being optional.free(ptr) ge...

First seen: 2026-07-23 06:57

Last seen: 2026-07-23 12:02