Design memory management subsystem
Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2021-07-06
Problem Statement
Design and implement a memory management subsystem that handles allocation, deallocation, and tracking of memory in a system or runtime environment. Focus on efficient memory usage, fragmentation handling, and performance.
Functional Requirements (FR)
Core Memory Management
•Allocate memory blocks of variable sizes.
•Free memory and make it available for reuse.
•Track memory usage per process or module.
•Support memory limits per process or allocation type.
Fragmentation Handling
•Minimize external fragmentation using techniques like buddy allocation or free lists.
•Support compaction or merging of adjacent free blocks.
Optional Features
•Garbage collection support for managed environments.
•Memory paging or swapping for virtual memory systems.
•Support for multiple allocation strategies: first-fit, best-fit, worst-fit.
•Memory leak detection and reporting.
Non-Functional Requirements (NFR)
•Performance → Low overhead for allocation/deallocation.
•Scalability → Handle large memory pools efficiently.
•Reliability → Prevent memory corruption, leaks, or double-free errors.
•Consistency → Maintain accurate allocation maps and free lists.
Core Entities & Attributes
MemoryBlock
•startAddress, size, isFree
MemoryPool / Heap
•totalSize, freeList[], allocatedList[]
Allocator
•strategy → Allocation strategy (first-fit, best-fit, buddy system)
•allocate(size): MemoryBlock
•free(block: MemoryBlock)
Core Components
Allocator Class
•Handles memory requests and releases.
•Implements allocation strategies.
MemoryPool / Heap Manager
•Maintains free and allocated memory blocks.
•Supports merging adjacent free blocks.
Garbage Collector (Optional)
•Reclaims unreachable memory.
•Supports mark-and-sweep or reference counting.
Memory Tracker / Monitor
•Tracks memory usage per process/module.
•Detects leaks, fragmentation, and threshold breaches.
APIs / Operations
Core APIs
•allocate(size: int): MemoryBlock → Returns allocated memory block.
•free(block: MemoryBlock) → Releases memory block.
•getMemoryUsage(): MemoryStats → Returns used, free, and total memory.
Optional APIs
•compact() → Merge fragmented memory blocks.
•setLimit(processId, size) → Restrict maximum memory allocation per process.
LLD Design Goals
•Class Diagram → MemoryBlock, MemoryPool, Allocator, GarbageCollector, MemoryTracker.
Design Patterns:
•Singleton → Single memory manager instance for a process.
•Strategy → To allow different allocation strategies.
•Concurrency Handling → Thread-safe allocation/deallocation in multithreaded environments.
•Trade-offs →1. Buddy system → fast allocation, moderate fragmentation.2. First-fit/Best-fit → simpler but may cause external fragmentation.3. Garbage collection → simplifies memory safety but adds runtime overhead