Memory Deallocation

1 / 5

free() is Simple

void my_free(void *ptr) {
    if (ptr == NULL) return;

    block_header_t *block = payload_to_block(ptr);
    block->free = 1;  // That's it!
}
2 / 5

Why Not Return to OS?

[A] [B] [C] <- heap top

Free B? Can't shrink heap.
C is in the way.
Just mark B for reuse.
3 / 5

Dangerous Operations

  • Double free: Corrupts allocator
  • Use after free: Data overwritten
  • Invalid free: Interprets garbage as header
4 / 5

Validation

// Magic number check
if (block->magic != BLOCK_MAGIC) abort();

// Double-free check
if (block->free) abort();
5 / 5
Use arrow keys or click edges to navigate. Press H to toggle help, F for fullscreen.