1 example

Memory fragmentation

Free memory becomes fragmented, reducing efficiency.

[ FAQ1 ]

What is memory fragmentation?

Memory fragmentation refers to a situation where free memory is split into scattered, disconnected blocks over time, typically resulting from continuous memory allocation and deallocation using functions like malloc() in languages such as C or C++. Fragmentation occurs primarily in heap memory, causing allocation requests for large contiguous blocks to fail even though sufficient total memory exists in smaller, non-adjacent chunks. This issue significantly impacts system performance, especially in embedded systems and long-running applications, by causing slower memory allocations, inefficient memory utilization, and sometimes even application failures due to allocation errors.
[ FAQ2 ]

How to fix memory fragmentation

To fix memory fragmentation, optimize memory allocation strategies to minimize frequent allocation and deallocation cycles. Use memory pools or fixed-size memory blocks to manage allocations efficiently, particularly in embedded systems. Leverage specialized allocators designed to reduce fragmentation, such as slab allocators or buddy allocators, depending on your application's needs. Regularly analyze your application's memory allocation patterns using profiling tools to identify and address fragmentation hotspots proactively. Additionally, periodically restarting long-running systems or applications can help reclaim fragmented memory and restore performance.
diff block
uint64_t heap_start;
uint64_t heap_end;
+uint32_t align_to(uint32_t addr, uint32_t align) {
+ uint32_t align_mask = align - 1;
+ if (addr & align_mask) {
+ return (addr | align_mask) + 1;
+ }
+ else {
+ return addr;
+ }
+}
+
mblock_t *find_heap_block(uint32_t size) {
HEAP_WALKER(mb) {
if (mb->free && mb->size > size) { // not >= ... little hack to not match last block in a byte
Greptile
greptile
style: The comment suggests this is intentional, but using > instead of >= for size comparison could lead to memory fragmentation by skipping perfectly usable blocks