How masoom-wahid/memioalloc works
Main Components
• Custom Memory Allocator Core: This includes the functions for allocating, deallocating, and reallocating memory.
• Memory Block Management: Represents the meta-data for each allocated block (size, status flags, pointers to the next and previous blocks, and a magic number for integrity).
• Heap Management: Illustrate how the allocator uses system calls:
• Using sbrk to expand the heap.
• Using mmap for large allocations (above a defined threshold).
• Free List Management: Show how free memory blocks are tracked and merged.
• Thread Safety: Represent the use of a mutex (pthread_mutex_t) to ensure that the operations are thread-safe.
• Debugging and Logging: Include components that log the internal state and perform stack trace debugging of memory blocks.
• API Interface: Highlight that the allocator exposes a public API (similar to malloc/free/realloc) and that users include memory.h in their programs.
Relationships and Interactions
• The User Program (or main function in src/main.c and main in the project root) interacts with the custom allocator through the public API.
• The allocator calls OS-level functions (sbrk for heap growth, mmap for larger chunks) to manage memory.
• All operations (allocation, deallocation, reallocation) pass through a locking mechanism before accessing/modifying the internal heap structure.
• Debugging tools are called either during normal operations or on demand to log the allocator’s state and the linked list structure of memory blocks.
Architectural Patterns and Design Principles
• Modular Design: Separation of interface (memory.h) and implementation (memory.c).
• Encapsulation: The internal heap and free list management details are hidden from the user.
• Concurrency: Thread safety as a cross-cutting concern implemented via mutex locks.
• Resource Management: Careful tracking of memory blocks to manage fragmentation and optimize allocation (including splitting/merging blocks).
Technologies and Libraries
• The C programming language and POSIX system calls (sbrk, mmap, munmap).
• POSIX Threads for thread safety.
• Standard C libraries for input/output and string manipulation where necessary.
Detailed Breakdown of Components
a. User Program Layer:
• Represented by main() functions (both the file in the root and src/main.c).
b. Custom Allocator API:
• Functions: mem_io_malloc, mem_io_free, mem_io_realloc, mem_io_log_trace, mem_io_stack_trace.
c. Memory Management Layer:
• Large Allocation Handling: Use a conditional pointer to mmap-based allocation.
d. Thread Safety:
• A component encapsulating all memory management functions with a mutex (pthread_mutex_t).
e. Debugging Tools:
• A separate but connected component that logs internal state and provides a stack trace of allocations.
f. OS Interaction: