Watching malloc() and free() work

A 4KB heap starting at virtual address 16KB, following the Free-Space Management chapter of OSTEP. Every allocated chunk begins with an 8-byte header: 4 bytes for its size and 4 bytes for a magic number. The allocator uses first fit, puts freed chunks at the front of the free list, and never coalesces.


  

Heap memory

Drawn to scale, the whole 4096-byte heap. The 100-byte chunks are thin slivers.

16KB 17KB 18KB 19KB 20KB

Zoomed in, byte addresses on the left, pointers on the right.

  • Header (size, magic)
  • Free-list node (size, next)
  • Data in use by a, b, c
  • Free space
20480

Program

Inside the 8 bytes

// while allocated
typedef struct {
  int size;   // 4 bytes
  int magic;  // 4 bytes
} header_t;

// while free
typedef struct __node_t {
  int size;
  struct __node_t *next;
} node_t;

Free list

Variables

Keyboard: ← → to step, Space to play or pause.