Skip to content
Tech News
← Back to articles

Why malloc always does more than I asked for?

read original more articles
Why This Matters

This article explores the inner workings of memory allocation in C, specifically why malloc often reserves more memory than requested. Understanding these nuances helps developers optimize memory usage and avoid unexpected overhead, which is crucial for performance-critical applications and efficient resource management in the tech industry.

Key Takeaways

void * p = malloc ( 13 );

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 bytes

that’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.

... continue reading