Memory Allocator Simulation
Overview
This simulation implements a basic memory allocator using a fixed-size array. It provides two primary functions:
malloc(size): Allocates a block of memory of the specified size.
free(ptr): Deallocates a previously allocated block of memory.
Implementation
class MemoryAllocator:
def __init__(self, total_memory):
"""
Initializes the memory allocator with a fixed-size array.
:param total_memory: The total size of the memory array.
"""
self.total_memory = total_memory
self.memory = [None] * total_memory
self.free_blocks = [(0, total_memory)] # (start, size)
def malloc(self, size):
"""
Allocates a block of memory of the specified size.
:param size: The size of the memory block to allocate.
:return: The starting index of the allocated memory block, or -1 if allocation fails.
"""
for i, (start, block_size) in enumerate(self.free_blocks):
if block_size >= size:
self.free_blocks.pop(i)
if block_size > size:
self.free_blocks.append((start + size, block_size - size))
for j in range(start, start + size):
self.memory[j] = 1 # Mark as allocated
return start
return -1 # Allocation failed
def free(self, ptr):
"""
Deallocates a previously allocated block of memory.
:param ptr: The starting index of the memory block to deallocate.
:return: True if deallocation is successful, False otherwise.
"""
if ptr < 0 or ptr >= self.total_memory:
return False
block_size = 0
while ptr + block_size < self.total_memory and self.memory[ptr + block_size] == 1:
block_size += 1
if block_size == 0:
return False # Not a valid allocated block
for i in range(ptr, ptr + block_size):
self.memory[i] = None # Mark as free
self.free_blocks.append((ptr, block_size))
self.free_blocks.sort() # Sort free blocks by start index
merged_blocks = [self.free_blocks[0]]
for current_start, current_size in self.free_blocks[1:]:
last_start, last_size = merged_blocks[-1]
if current_start == last_start + last_size:
merged_blocks[-1] = (last_start, last_size + current_size)
else:
merged_blocks.append((current_start, current_size))
self.free_blocks = merged_blocks
return True
# Example usage:
allocator = MemoryAllocator(10)
ptr1 = allocator.malloc(3)
print(ptr1) # Output: 0
ptr2 = allocator.malloc(2)
print(ptr2) # Output: 3
allocator.free(ptr1)
ptr3 = allocator.malloc(4)
print(ptr3) # Output: 0
Explanation
- The
MemoryAllocator class initializes with a fixed-size array and a list of free blocks.
- The
malloc(size) function iterates through the free blocks to find a suitable block that can accommodate the requested size. If found, it allocates the block, marks it as allocated, and updates the free blocks list.
- The
free(ptr) function deallocates a previously allocated block by marking it as free and merging adjacent free blocks.
This implementation provides a basic memory allocation and deallocation mechanism using a fixed-size array. However, it's essential to note that this is a simplified simulation and may not cover all edge cases or optimize for performance.