Chunk allocation and reallocation

Bins exist to reuse chunks. Here there is a quick example at how it's done.


Fastbins are probably the easiest to explain as they are grouped by size.

The last chunk to be placed in the bin is the first chunk reallocated.

A simple C program can highlight this behavior :

#include <stdio.h>
#include <stdlib.h>

int main() {
    char *a = malloc(20);
    char *b = malloc(20);
    char *c = malloc(20);
    printf("a: %p\nb: %p\nc: %p\n", a, b, c);




    char *d = malloc(20);
    char *e = malloc(20);
    char *f = malloc(20);

    printf("d: %p\ne: %p\nf: %p\n", d, e, f);
a: 0x55c9fe6de2a0
b: 0x55c9fe6de2c0
c: 0x55c9fe6de2e0
d: 0x55c9fe6de2e0
e: 0x55c9fe6de2c0
f: 0x55c9fe6de2a0

This specific fastbin progresses as follows:

And then when data are reallocated :

the chunk a gets reassigned to chunk f, b to e and c to d.

Then, if a chunk is freed, thee is a good chance that the next malloc() - if it's the same size - will use the same chunk

Unsorted Bins

When a non-fast chunk is freed, it gets put into the Unsorted Bin. When new chunks are requested, glibc looks at the unsorted bin.

  • If the requested size is equal to the size of the chunk in the bin, return the chunk

  • If it's smaller, split the chunk in the bin in two and return a portion of the correct size

Last updated