How can I encourage malloc() to return a series of consecutive allocations?
14:57 18 Jun 2026

I've observed that when I write a little test program that builds a linked list and prints the addresses, they tend to be consecutive. This is a very cache-efficient behavior, since the nodes pack densely and the CPU's prefetcher can easily detect the access pattern and prefetch subsequent nodes.

What I'd like to know is whether there's any way to achieve similar behavior, when a program has been running for a while and the heap is quite fragmented. Particularly with glibc.

I'm aware that I could do my own large allocation and subdivide, but that has its own limitations and pitfalls. So, I'm hoping there's a trick for simply encouraging malloc() to give me more coherent and contiguous allocations of a given size.

optimization caching malloc glibc