pointers-memory · advanced · ~15 min
Implement allocator block coalescing to counteract heap memory fragmentation.
Dynamic memory allocators (like dlmalloc and ptmalloc) suffer from external fragmentation when small blocks are freed. Coalescing traverses adjacent free blocks and merges them into a single larger block.
Implement:
struct chunk_hdr {
size_t size;
int is_free;
struct chunk_hdr *next;
};
int coalesce_free_chunks(struct chunk_hdr *head);
Traverse the chunk list starting at head. Whenever two adjacent chunks are both free (curr->is_free && curr->next->is_free), coalesce them.
curr->size += sizeof(struct chunk_hdr) + curr->next->size.curr->next = curr->next->next.curr immediately, because the newly enlarged chunk may be adjacent to another free chunk.head: pointer to first chunk_hdr in linked list.
Returns integer count of coalesced merges.
C11 freestanding. In-place linked list manipulation.
#include <stddef.h>
/* The harness provides:
struct chunk_hdr {
size_t size;
int is_free;
struct chunk_hdr *next;
};
*/
int coalesce_free_chunks(struct chunk_hdr *head) {
(void)head;
return 0;
}
Advancing curr before checking if curr->next is also free; forgetting to include sizeof(struct chunk_hdr) in merged size.
No free chunks returns 0; multiple consecutive free chunks all merge into one; single chunk list.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.