Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Dynamic Memory Heap allocator

A lightweight, zero-dependency custom memory allocator built from scratch in C. This project bypasses the standard library's malloc and free functions, directly requesting memory from the Linux kernel using the mmap system call.

Features

  • Zero Dependencies: Does not rely on <stdlib.h> memory functions.
  • Direct Kernel Allocation: Uses mmap for initial heap allocation (MAP_PRIVATE | MAP_ANONYMOUS).
  • First-Fit Algorithm: Efficiently finds available memory blocks.
  • Block Splitting: Reduces internal fragmentation by splitting large blocks into smaller, exact-fit chunks.
  • Memory Coalescing: Merges adjacent free blocks during free() to prevent external fragmentation.
  • Aligned Memory: Ensures memory addresses are correctly aligned (8-byte boundaries) for CPU read efficiency.

Project Structure

Implementing-Dynamic-Memory-Heap-allocator
 ┣ src
 ┃ ┣ allocator.c
 ┃ ┗ allocator.h
 ┣ Makefile
 ┣ README.md
 ┗ main.c
  • src/allocator.h: The public API and Block Header structure.
  • src/allocator.c: The core logic handling memory blocks, splitting, and coalescing.
  • main.c: Test cases demonstrating allocation, reallocation, and freeing.

Getting Started

Prerequisites

  • A Linux-based OS (utilizes <sys/mman.h>).
  • GCC Compiler.
  • Make.

API Reference

// Initialize the heap (must be called before any allocations)
void mem_init(void);

// Allocate memory
void* mem_malloc(size_t size);

// Reallocate memory to a new size
void* mem_realloc(void* ptr, size_t new_size);

// Free allocated memory
void mem_free(void* ptr);

Build and Run

Clone the repository and use the provided Makefile:

git clone [https://github.com/abdelhalimyasser/Implementing-Dynamic-Memory-Heap-allocator.git](https://github.com/abdelhalimyasser/Implementing-Dynamic-Memory-Heap-allocator.git)
cd Implementing-Dynamic-Memory-Heap-allocator
make run

How It Works

  1. Initialization: Requests a contiguous block of memory of 64KB directly from the OS using mmap.

  2. Metadata: Prepend a hidden BlockHeader struct to each allocated memory chunk to track its size, is_free status, and the next block in the linked list.

  3. Allocation: Traverses the linked list to find the first free block large enough. If the block is significantly larger than requested, it splits it into two blocks.

  4. Deallocation: Marks the block as free and immediately checks adjacent blocks to coalesce them into a single larger free block.

About

A zero-dependency, thread-safe-ready custom memory allocator built from scratch in C using Linux mmap system calls. Features include block splitting and memory coalescing.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages