MicroHeap is a custom implementation of dynamic memory allocation functions (malloc, free, calloc, realloc) built from scratch using low-level system calls. This project demonstrates fundamental concepts of memory management including heap manipulation, memory alignment, with thread safety.
- Custom Memory Allocation: Drop-in replacements for standard C memory functions
- Thread-Safe: Uses pthread mutexes to ensure safe concurrent access
- Memory Alignment: Implements 32-byte alignment for optimal performance
- Smart Memory Management: Returns memory to OS when possible, reuses freed blocks
- Zero Initialization: Supports
callocwith proper zero-initialization - Memory Reallocation: Efficient
reallocwith data preservation - Overflow Protection: Built-in overflow checks in
calloc
Memory Block Structure: ┌────────────────────────────────────────┐ │ Header (32 bytes aligned) │ │ ┌──────────────────────────────────┐ │ │ │ size: Size of the block │ │ │ │ is_free: Free/allocated flag │ │ │ │ next: Pointer to next block │ │ │ └──────────────────────────────────┘ │ ├────────────────────────────────────────┤ │ User Data Area │ │ (requested memory) │ │ │ └────────────────────────────────────────┘ -
Block Header: Metadata structure hidden from users(calling functions)
- Size tracking
- Free/allocated status
- Linked list for block management
-
Memory Alignment: 16-byte alignment using
ALIGN16macro -
Thread Safety: Global mutex lock for all operations
-
Free List Management: Maintains linked list of all blocks
Allocates a block of memory.
- Parameters to be Passed:
size- Number of bytes to allocate - Returns: Pointer to allocated memory, or
NULLon failure
Frees a previously allocated block.
- Parameters to be Passed:
block- Pointer to memory to free - Behavior: Returns memory to OS if at end of heap, otherwise marks as free
Allocates and zero-initializes memory for an array.
- Parameters to be Passed:
num- Number of elements,nsize- Size per element - Returns: Pointer to zeroed memory, or
NULLon failure
Resizes an existing memory block.
- Parameters to be Passed:
block- Existing block,size- New size - Returns: Pointer to resized block, or
NULLon failure
- GCC or Clang compiler
- POSIX-compliant system (Linux, macOS, Unix)
- pthread library
# Compile the library with your program gcc -o example example_program.c microheap.c -lpthread # Run the example ./example#include "microheap.h" int main() { // Allocate memory int *arr = my_malloc(sizeof(int) * 10); // Use the memory for (int i = 0; i < 10; i++) { arr[i] = i * 2; } // Free the memory my_free(arr); return 0; }Run example_program.c to see comprehensive demonstrations:
╔═══════════════════════════════════════════════╗ ║ MICROHEAP MEMORY ALLOCATOR DEMO ║ ║ Custom malloc/free/calloc/realloc ║ ╚═══════════════════════════════════════════════╝ ================================================= TEST 1: my_malloc() ================================================= ✅ Successfully allocated memory for 10 integers Writing values: 10 20 30 40 50 60 70 80 90 100 ... -
Allocation Process:
- Searches for free block in existing list
- If found, marks it as allocated and returns
- Otherwise, requests memory from OS using
sbrk() - Adds new block to linked list
-
Deallocation Process:
- Checks if block is at end of heap
- If yes, returns memory to OS via
sbrk() - Otherwise, marks block as free for reuse
-
Reallocation Process:
- If new size fits in current block, returns same pointer
- Otherwise, allocates new block, copies data, frees old block
- No Block Splitting: Large free blocks aren't split for smaller requests
- No Coalescing: Adjacent free blocks aren't merged (fragmentation)
- Debug Output: Contains printf statements that should be removed for production
- Limited Error Handling: Basic error checking, could be more robust
- Performance: Not optimized for high-performance scenarios
- Implement block splitting for better memory utilization
- Add block coalescing to reduce fragmentation
- Remove debug printf statements
- Add memory usage statistics and diagnostics
- Implement best-fit or first-fit strategies
- Add boundary checking for buffer overflow detection
- Optimize alignment and reduce overhead
- Add memory pool support for fixed-size allocations
Feel free to fork, improve, and submit pull requests. This is an educational project!
MIT License - Feel free to use this code for learning and experimentation.