Skip to content

Commit 44eed33

Browse files
committed
Add split_block() helper
Splitting a large memory block into two smaller blocks is a common operation in the allocator. Introduce a split_block() helper to centralize this functionality and avoid repeating the same code. The helper also panics if the split size is invalid, ensuring stronger consistency checks in the allocator.
1 parent 48df0e2 commit 44eed33

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

lib/malloc.c

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,28 @@ static void selective_coalesce(void)
135135
}
136136
}
137137

138+
static inline void split_block(memblock_t *block, size_t size)
139+
{
140+
size_t remaining;
141+
memblock_t *new_block;
142+
143+
if (unlikely(size >= GET_SIZE(block))) {
144+
panic(ERR_HEAP_CORRUPT);
145+
return;
146+
}
147+
remaining = GET_SIZE(block) - size;
148+
/* Split only when remaining memory is large enough */
149+
if (remaining < sizeof(memblock_t) + MALLOC_MIN_SIZE)
150+
return;
151+
new_block = (memblock_t *) ((size_t) block + sizeof(memblock_t) + size);
152+
new_block->next = block->next;
153+
new_block->size = remaining - sizeof(memblock_t);
154+
MARK_FREE(new_block);
155+
block->next = new_block;
156+
block->size = size | IS_USED(block);
157+
free_blocks_count++; /* New free block created */
158+
}
159+
138160
/* O(n) first-fit allocation with selective coalescing */
139161
void *malloc(uint32_t size)
140162
{

0 commit comments

Comments
 (0)