Beyond Dynamic Arrays: The Efficient and Stable Segment Array

This article introduces Segment Array, a high-performance data structure combining the flexibility of dynamic arrays, the advantages of stable pointers, and excellent compatibility with arena allocators. Unlike dynamic arrays that move elements during resizing, Segment Array uses pre-allocated segments of fixed sizes, avoiding memory fragmentation and pointer invalidation. Each segment is double the size of its predecessor, with new segments allocated only when needed, achieving O(1) average time complexity. The author provides a C implementation and details its inner workings, including efficient index calculation and integration with generics. Segment Array is particularly useful in scenarios requiring efficient dynamic memory management within an arena allocator, such as in a build profiler.