A fixed C array is allocated once and never changes size. A dynamic array keeps a buffer, a count of used elements and a count of allocated slots, and when the buffer fills it asks realloc for a bigger one. In the experiment below, one million appends under a doubling policy caused 17 reallocations that could have copied up to 4.2 MB of old buffers, and the 1.5 policy caused 29 reallocations and up to 8.0 MB. The copies are amortized work, not per-push work, and the growth factor decides how often they happen and how much memory the array holds in reserve.
This guide implements a growable int vector in C: the structure, the growth policy, realloc failure handling, reserve and shrink_to_fit, and five pointer mistakes that realloc invites, each caught by a sanitizer. The Arrays article covers fixed arrays and memory layout, and the std::vector guide covers the C++ container this code is modeled on. This article focuses on writing the vector yourself in C. The code was built and tested on Ubuntu 24.04 under WSL2 with GCC and Clang and on Windows 11 with MSVC, and every output block below comes from a real run.
What Is a Dynamic Array?
A dynamic array is an array that owns a heap buffer and grows it on demand. It keeps a size for the values in use and a capacity for the slots allocated, and when a push finds size equal to capacity it moves the values into a larger buffer and continues. The result keeps O(1) indexing and amortized O(1) appends while the capacity follows the demand.
The two numbers are the whole design. size says how many values are alive and is what the caller sees, while capacity says how many slots the buffer has and is invisible except through performance and memory use. The invariant is size <= capacity, and every operation preserves it. Indexing is data[i] after a bounds check, which is O(1) and as cache-friendly as the fixed array it replaces. Appending is O(1) most of the time and O(capacity) when the buffer must grow, and the growth is chosen so that the expensive case is rare enough to average out.
The classic amortized argument says why the policy matters. If the capacity doubles when full, the copies over n appends total at most 2n elements, so the average copy per append is a constant even though individual appends can copy the whole array. Growth factors below 2 copy more in total but keep the spare memory smaller, and factors above 2 copy less but waste more slots. That trade-off is exactly what the growth experiment measures, and the waste is not free in a program that holds many small arrays.
The cache behavior is worth stating separately. A contiguous buffer gives the CPU a prefetch-friendly walk and a single allocation, while pointer-linked structures can pay a cache miss per element. The growth copy is the price paid for that layout, and it is paid rarely.
The alternatives explain the niche. A fixed array cannot grow. A linked list grows in O(1) but loses indexing and cache locality. A block-based container, such as a deque, grows at the ends without copying everything but is not one contiguous buffer. A dynamic array is the right default when indexing, iteration and a compact buffer matter and appends dominate, which is why std::vector, Java’s ArrayList, C#’s List<T> and Python’s list all use a growable contiguous buffer.
How This Was Measured
| Setting | Value |
|---|---|
| Date tested | December 1, 2026 |
| Hardware | Intel Core i7-8700K, 6 cores and 12 threads at 3.70 GHz, 32 GB RAM, Windows 11 Education build 26300 |
| Operating system | Ubuntu 24.04.5 under WSL2, kernel 5.15.146.1-microsoft-standard-WSL2, glibc 2.39; Windows 11 for the MSVC build |
| Compilers | GCC 13.3 and Clang 18.1.3 at -O2 through CMake Release; MSVC 19.44 at /W4 /WX |
| Growth experiment | 1,000,000 int appends from an initial capacity of 8, for growth factors 2, 1.5 and 1.25, plus a reserve-exact baseline |
| Churn experiment | 1,000,000 appends followed by 900,000 pops, then shrink_to_fit |
| What is timed | The append loop per policy. The experiment tracks capacities and copy volumes itself with malloc/realloc and the same growth rules as the article’s code |
| Statistic | Single run per policy, milliseconds. Capacities, reallocation counts and copied bytes are deterministic |
| Check | Every policy must end with the same values and checksum, and the churn run must keep the same remaining values before and after shrinking |
No CPU pinning or frequency scaling control was used, and the host runs other software, so the times are indicative for this machine and the counts are the reproducible part. All numbers come from one machine and one WSL2 instance.
The Growth Policy: Reallocations, Copies and Waste
The shipped array doubles: new_capacity = capacity == 0 ? 8 : capacity * 2, with an overflow guard for capacities near SIZE_MAX. A push that finds the buffer full calls realloc for the new capacity and stores the result in a temporary pointer. realloc either extends the block in place or allocates a new one, copies the values and frees the old one. The temporary is the whole safety story: if realloc returns NULL, the old pointer is still valid, the array is unchanged, and the push reports failure instead of losing the buffer.
The experiment runs each policy on its own small vector rather than the article’s IntArray, so the capacity sequence and the copy volume are explicit. Its copied-bytes column counts the old buffer at every reallocation, which is what realloc must copy when it cannot extend the block in place. The reserve baseline calls malloc once and then pushes without any growth, which is why its column is zero.
The growth factor is a policy, not a law. Doubling gives the fewest reallocations and the largest jumps, 1.5 gives more reallocations and smaller jumps, and 1.25 more and smaller still.
The copies over n appends are a geometric series, so the factor changes the constant: doubling copies at most about 2n elements in total, 1.5 about 3n, and 1.25 about 5n. The waste right after a growth is (factor - 1) * old_capacity, so doubling can hold up to half its slots empty and 1.5 up to a third. The final waste at a particular n also depends on where n falls between two growth points, which is why the table includes the peak waste as well as the final waste.
Why Not realloc on Every Push?
The first design question is why not call realloc for every push and skip the capacity policy. The answer is the copied bytes. If every append reallocates to exactly size + 1 and every realloc has to move the block, the millionth push copies about 4 MB and the total is near 2 TB. That is quadratic in the number of appends. An allocator that can often extend a block in place hides some of the cost, but nothing in the C standard promises it, and every call still pays for the allocator itself.
The experiment’s reserve baseline shows the other extreme: one allocation of exactly one million slots, zero reallocations and zero bytes copied during the growth phase, at the cost of holding the final capacity from the start. The capacity policy sits between those extremes and trades copying against spare memory, and the geometric series is what turns the worst case into an amortized constant.
The same arithmetic explains why the policy belongs inside the container rather than in the caller. A caller that pushes in a loop cannot know when the buffer will fill, and a caller that reserves exactly the final size has to know that size in advance. The container knows both the current size and the current capacity, so it is the only layer that can make the trade on every push. That is also why the standard containers expose reserve as a hint rather than a requirement.
Dynamic Array Implementation in C
The structure is three fields and a set of functions that keep them consistent. The article’s code puts the whole type in src/darray.c so the demo can be a single translation unit, and the tests include the same file with main renamed, which is the repository’s convention for testing static helpers directly.
static bool array_grow(IntArray *array)
{
size_t new_capacity;
int *new_data;
if (array->capacity == 0) {
new_capacity = (size_t)ARRAY_MIN_CAPACITY;
} else {
if (array->capacity > SIZE_MAX / 2)
return false;
new_capacity = array->capacity * 2;
}
if (new_capacity > SIZE_MAX / sizeof *new_data)
return false;
new_data = realloc(array->data, new_capacity * sizeof *new_data);
if (new_data == NULL)
return false;
array->data = new_data;
array->capacity = new_capacity;
return true;
}
bool array_push(IntArray *array, int value)
{
if (array->size == array->capacity && !array_grow(array))
return false;
array->data[array->size] = value;
array->size++;
return true;
}
bool array_reserve(IntArray *array, size_t new_capacity)
{
int *new_data;
if (new_capacity <= array->capacity)
return true;
if (new_capacity > SIZE_MAX / sizeof *new_data)
return false;
new_data = realloc(array->data, new_capacity * sizeof *new_data);
if (new_data == NULL)
return false;
array->data = new_data;
array->capacity = new_capacity;
return true;
}
/* Reallocates to exactly size slots. An empty array frees the buffer and resets
* the capacity to 0. Returns false on allocation failure, and then the array is
* unchanged. */
bool array_shrink_to_fit(IntArray *array)
{
int *new_data;
if (array->size == 0) {
free(array->data);
array->data = NULL;
array->capacity = 0;
return true;
}
if (array->capacity == array->size)
return true;
new_data = realloc(array->data, array->size * sizeof *new_data);
if (new_data == NULL)
return false;
array->data = new_data;
array->capacity = array->size;
return true;
}
array_push is the only function that grows the buffer, and array_reserve is the only other path to a larger allocation. reserve is grow-only, like std::vector::reserve: asking for a capacity the array already has changes nothing, even when the request is smaller than the current size. That asymmetry is deliberate, because shrink_to_fit is the one operation that lowers the capacity, and it is explicit because it costs a reallocation and a copy.
Output:
dynamic int array, initial capacity 2
push 10, 20 -> size 2, capacity 2
push 30 -> size 3, capacity 4
values: 10 20 30
get 1 -> 20, get 3 -> out of range
set 1 to 25 -> values: 10 25 30
pop -> 30, size 2, capacity 4
reserve 10 -> size 2, capacity 10
shrink_to_fit -> size 2, capacity 2
clear -> size 0, capacity 2
The Cost of Growing: Measured
The growth experiment pushes one million ints under each policy and records what the growth did: how many reallocations happened, how many bytes the old buffers held when they were copied, the final capacity, the final waste and the largest waste seen immediately after a growth.
static size_t next_capacity(size_t capacity, unsigned numerator,
unsigned denominator)
{
size_t grown = (capacity / denominator) * numerator
+ (capacity % denominator) * numerator / denominator;
if (grown <= capacity)
grown = capacity + 1;
return grown;
}
static void grow_vec_push(GrowVec *vector, int value, unsigned numerator,
unsigned denominator)
{
if (vector->size == vector->capacity) {
size_t old_capacity = vector->capacity;
size_t new_capacity = next_capacity(old_capacity, numerator, denominator);
int *new_data;
if (new_capacity > SIZE_MAX / sizeof *new_data)
fail("capacity overflow");
new_data = realloc(vector->data, new_capacity * sizeof *new_data);
if (new_data == NULL)
fail("out of memory");
vector->data = new_data;
vector->capacity = new_capacity;
vector->reallocations++;
vector->bytes_copied += old_capacity * sizeof *new_data;
if (new_capacity - vector->size > vector->peak_wasted)
vector->peak_wasted = new_capacity - vector->size;
}
vector->data[vector->size] = value;
vector->size++;
}
/* The reserve-exact baseline: one allocation of the requested capacity before
* the append loop. It is not a growth, so no counter moves. */
static void grow_vec_reserve(GrowVec *vector, size_t capacity)
{
int *new_data;
if (capacity <= vector->capacity)
return;
if (capacity > SIZE_MAX / sizeof *new_data)
fail("reserve capacity overflow");
new_data = realloc(vector->data, capacity * sizeof *new_data);
if (new_data == NULL)
fail("out of memory");
vector->data = new_data;
vector->capacity = capacity;
}
Output:
1,000,000 int appends, initial capacity 8
policy reallocations bytes_copied final_capacity wasted_slots peak_wasted time_ms
grow x2 17 4194272 1048576 48576 524288 2.704
grow x1.5 29 8042468 1005310 5310 335103 2.022
grow x1.25 54 17956076 1122241 122241 224448 1.230
reserve exact 0 0 1000000 0 0 1.610
The columns to read are not the milliseconds. Doubling reallocated 17 times over old buffers totaling 4,194,272 bytes (about 4.2 MB), 1.5 reallocated 29 times over 8,042,468 bytes (8.0 MB), and 1.25 reallocated 54 times over 17,956,076 bytes (18.0 MB). The reserve baseline caused no reallocation and no copies at all.
The peak waste column is the structural difference: 524,288 spare slots immediately after a doubling, 50% of the capacity, against 335,103 (33%) for 1.5 and 224,448 (20%) for 1.25, which is the (factor – 1) bound in practice. The final waste is noisier. This run ended with 48,576 spare slots under doubling (4.6%), 5,310 under 1.5 (0.5%) and 122,241 under 1.25 (10.9%), because the final capacity depends on where one million lands between two growth points. The times, 1.2 to 2.7 ms, are small enough that allocator behavior and noise dominate them, so the counts and bytes are the result.
Memory Retained After Popping
Popping values lowers size but never lowers capacity: the buffer keeps its slots, which is the point of an array that will be filled again. The churn experiment appends a million values, pops nine hundred thousand, and then calls shrink_to_fit to show what the capacity costs before and after the explicit release.
static void vec_grow(IntVec *vector)
{
size_t new_capacity = vector->capacity == 0 ? (size_t)MIN_CAPACITY
: vector->capacity * 2;
int *new_data;
if (new_capacity > SIZE_MAX / sizeof *new_data)
fail("capacity overflow");
new_data = realloc(vector->data, new_capacity * sizeof *new_data);
if (new_data == NULL)
fail("out of memory");
vector->data = new_data;
vector->capacity = new_capacity;
}
static void vec_shrink_to_fit(IntVec *vector)
{
int *new_data;
if (vector->size == 0) {
free(vector->data);
vector->data = NULL;
vector->capacity = 0;
return;
}
if (vector->capacity == vector->size)
return;
new_data = realloc(vector->data, vector->size * sizeof *new_data);
if (new_data == NULL)
fail("shrink_to_fit failed");
vector->data = new_data;
vector->capacity = vector->size;
}
Output:
1,000,000 appends then 900,000 pops
stage size capacity resident_bytes
after appends 1000000 1048576 4194304
after pops 100000 1048576 4194304
after shrink_to_fit 100000 100000 400000
checksum: 9259950532764359811
After a million appends the array held 1,048,576 slots, 4,194,304 bytes, for 1,000,000 values. Popping 900,000 values reduced the size to 100,000 but left every slot allocated, so the buffer still held 4,194,304 bytes. shrink_to_fit reallocated to exactly 100,000 slots, 400,000 bytes, and released 3,794,304 bytes (3.8 MB), with the remaining values and the checksum unchanged.
The cost is one reallocation and at most one copy of the live values, so doing it once after a burst is cheaper than shrinking after every pop. That is the trade the type offers: capacity is kept for the next burst of appends, and the program decides when the memory is worth more than the future writes.
The Failure Path and the Overflow Guard
The happy path is the copy, and the failure path is what makes the type safe. realloc returns NULL when the request cannot be satisfied and leaves the old block untouched, so the array must only swap buffers after checking the result. The growth helper does exactly that: it computes the new capacity, calls realloc into a temporary pointer, returns false on NULL, and only then updates data and capacity. The push propagates the false to its caller and the array stays valid, which the tests exercise with an impossible reserve request that must leave the array unchanged.
The second guard is arithmetic. Doubling multiplies a size_t by two, and a capacity above SIZE_MAX / 2 wraps around, and a wrapped value can be smaller than the current size, which would make the next realloc shrink the buffer and the next push write past its end. The growth helper checks the capacity bound and the byte-size multiplication before allocating, and the tests drive the byte-size guard with reserve and init requests just past SIZE_MAX / sizeof(int). Neither guard costs anything measurable in the append loop, and both are the difference between a failure that reports an error and a failure that corrupts memory silently.
Where the Other Languages Land
The same design appears in every standard library, with different policies and names. This article implements the C version, and the others are listed so the same trade-offs can be recognized when using them.
| Language | Container | Growth policy | Reserve | Shrink |
|---|---|---|---|---|
| C | this article | doubles from 8 | array_reserve, grow-only | array_shrink_to_fit |
| C++ | std::vector | implementation-defined geometric | reserve, grow-only | shrink_to_fit |
| Java | ArrayList | about 1.5 times | ensureCapacity, grow-only | trimToSize |
| C# | List<T> | doubles | Capacity / EnsureCapacity | TrimExcess |
| Python | list | over-allocates geometrically | none exposed | none |
The growth factors are implementation details rather than laws: Java’s ArrayList has used about 1.5 since early versions and the C++ standard says only that std::vector grows geometrically, so the exact capacity jump can change between library versions. Python’s list over-allocates but exposes no capacity, which is why reserve does not appear in its row. The C++ container is described in the cppreference std::vector page, Java’s in the ArrayList documentation, Python’s list in the data structures tutorial, and C#’s in the List<T> documentation. The C realloc semantics this code depends on are on cppreference as well.
When a Dynamic Array Is the Wrong Choice
The array wins when the values are contiguous, indexed and appended in bulk. It loses when the workload inserts or deletes in the middle repeatedly: every operation moves the tail, which is O(n), and no growth policy changes that. A linked list keeps those operations O(1) when the node is held, at the cost of extra pointers per value, scattered nodes on every walk and no indexing. That is the trade the doubly linked list article measures. A block-based container such as a deque keeps O(1) operations at both ends and avoids one huge copy, but middle insertions still move data and indexing adds a level of indirection.
The array also loses when the program holds many small arrays that grow unpredictably: the spare capacity of each is memory held against a future growth that may never come, which is why reserving or shrinking to the expected size matters more than the growth factor in that regime. When the maximum size is known and fixed, a plain array and a count is simpler than any growable type. The dynamic array is a default, not a universal answer, and the cost it trades away is the ability to move values cheaply.
Five Ways a Dynamic Array Passes a Quick Test and Still Fails
Each of these programs compiles cleanly with -Wall -Wextra -pedantic and prints something plausible until the line below it, or until a sanitizer stops it. The workflows re-run each and assert the line or the sanitizer summary.
1. The Alias That Outlives realloc
static bool array_push(IntArray *array, int value)
{
if (array->size == array->capacity) {
size_t new_capacity = array->capacity == 0 ? 8 : array->capacity * 2;
int *new_data = realloc(array->data, new_capacity * sizeof *new_data);
if (new_data == NULL)
return false;
array->data = new_data;
array->capacity = new_capacity;
}
array->data[array->size] = value;
array->size++;
return true;
}
int main(void)
{
IntArray array;
int *alias;
size_t index;
setvbuf(stdout, NULL, _IONBF, 0);
puts("dangling_alias: an alias to the old buffer is used after the push grows it");
array.data = malloc(4 * sizeof *array.data);
if (array.data == NULL) {
fputs("out of memory\n", stderr);
return EXIT_FAILURE;
}
array.size = 0;
array.capacity = 4;
for (index = 0; index < 4; ++index) {
if (!array_push(&array, (int)(10 * (index + 1)))) {
fputs("push failed\n", stderr);
return EXIT_FAILURE;
}
}
alias = array.data;
printf("capacity %zu: alias saved the address of the 4-slot buffer\n",
array.capacity);
if (!array_push(&array, 50)) {
fputs("push failed\n", stderr);
return EXIT_FAILURE;
}
printf("push 50 grew capacity to %zu: realloc moved the buffer\n",
array.capacity);
puts("writing alias[0] = 99 through the stale pointer");
alias[0] = 99; /* heap-use-after-free: the old buffer is gone */
printf("alias[0] = %d, size %zu\n", alias[0], array.size);
free(array.data);
return EXIT_SUCCESS;
}
Output:
dangling_alias: an alias to the old buffer is used after the push grows it
capacity 4: alias saved the address of the 4-slot buffer
push 50 grew capacity to 8: realloc moved the buffer
writing alias[0] = 99 through the stale pointer
Output (summarized from the AddressSanitizer report):
AddressSanitizer: heap-use-after-free
WRITE of size 4 at pitfalls/dangling_alias.c:70 (main)
16-byte region freed by realloc at pitfalls/dangling_alias.c:27 (array_push)
16-byte region previously allocated by malloc at pitfalls/dangling_alias.c:47 (main)
SUMMARY: AddressSanitizer: heap-use-after-free pitfalls/dangling_alias.c:70 in main
The push function itself handles growth correctly with a temporary realloc pointer, but main keeps an alias to the old buffer across the push. The push grows the array, realloc moves it, and the alias now points at freed memory. AddressSanitizer reports a heap-use-after-free on the write, with the freed region identified as the old buffer inside array_push. Under AddressSanitizer realloc always moves the block, so the bug shows on every run, while a normal build fails only when the allocator happens to move it. The array never knew about the alias, which is why interior pointers into a growable buffer are unsafe across any operation that can grow it.
2. clear That Forgets to Reset
static bool array_push(IntArray *array, int value)
{
if (array->size == array->capacity) {
size_t new_capacity = array->capacity == 0 ? 8 : array->capacity * 2;
int *new_data = realloc(array->data, new_capacity * sizeof *new_data);
if (new_data == NULL)
return false;
array->data = new_data;
array->capacity = new_capacity;
}
array->data[array->size] = value;
array->size++;
return true;
}
/* The bug: the buffer is freed, but the array still claims the old size and
* capacity. The data pointer is not reset either. */
static void array_clear_broken(IntArray *array)
{
free(array->data);
}
Output:
clear_without_reset: clear frees the buffer but leaves size and capacity
clear freed the buffer and left size 3, capacity 4
push 40 writes data[3] through the freed buffer
Output (summarized from the AddressSanitizer report):
AddressSanitizer: heap-use-after-free
WRITE of size 4 at pitfalls/clear_without_reset.c:33 (array_push)
16-byte region freed by free at pitfalls/clear_without_reset.c:42 (array_clear_broken)
16-byte region previously allocated by malloc at pitfalls/clear_without_reset.c:52 (main)
SUMMARY: AddressSanitizer: heap-use-after-free pitfalls/clear_without_reset.c:33 in array_push
The broken clear frees the buffer and leaves size and capacity untouched, which looks fine until the next push. The array believes it still has capacity, writes at data[size], and AddressSanitizer reports a heap-use-after-free on the freed 16-byte buffer. The correct clear sets size to 0 and keeps the buffer, while a destroy frees it and resets the pointer, size and capacity together.
3. A Push Without a Growth Check
static bool array_push_broken(IntArray *array, int value)
{
array->data[array->size] = value;
array->size++;
return true;
}
int main(void)
{
IntArray array;
size_t index;
setvbuf(stdout, NULL, _IONBF, 0);
puts("push_without_grow: push writes data[size] when the buffer is full");
array.size = 0;
array.capacity = 8;
array.data = malloc(array.capacity * sizeof *array.data);
if (array.data == NULL) {
fputs("out of memory\n", stderr);
return EXIT_FAILURE;
}
for (index = 0; index < array.capacity; ++index)
(void)array_push_broken(&array, (int)(10 * (index + 1)));
printf("size %zu, capacity %zu: the buffer has no spare slot\n", array.size,
array.capacity);
puts("push 90 writes data[8] one slot past the end of the 8-slot buffer");
(void)array_push_broken(&array, 90);
printf("push 90 reported success, size %zu\n", array.size);
free(array.data);
return EXIT_SUCCESS;
}
Output:
push_without_grow: push writes data[size] when the buffer is full
size 8, capacity 8: the buffer has no spare slot
push 90 writes data[8] one slot past the end of the 8-slot buffer
Output (summarized from the AddressSanitizer report):
AddressSanitizer: heap-buffer-overflow
WRITE of size 4 at pitfalls/push_without_grow.c:24 (array_push_broken)
32-byte region allocated by malloc at pitfalls/push_without_grow.c:38 (main)
SUMMARY: AddressSanitizer: heap-buffer-overflow pitfalls/push_without_grow.c:24 in array_push_broken
The push writes at data[size] without checking whether size has reached capacity. Eight values fill the 32-byte buffer, push 90 writes data[8] one slot past the end, and AddressSanitizer reports a heap-buffer-overflow on the write. The lesson is the invariant, not the check: every push must either already have room or grow, and a test that only pushes within the initial capacity never sees the bug.
4. Losing the Old Pointer When realloc Fails
static bool array_push(IntArray *array, int value)
{
if (array->size == array->capacity) {
size_t new_capacity = array->capacity == 0 ? 8 : array->capacity * 2;
int *new_data = realloc(array->data, new_capacity * sizeof *new_data);
if (new_data == NULL)
return false;
array->data = new_data;
array->capacity = new_capacity;
}
array->data[array->size] = value;
array->size++;
return true;
}
int main(void)
{
IntArray array;
size_t index;
/* volatile keeps the compiler from proving the request impossible at
* compile time, so the failure happens in realloc at run time, where the
* lost pointer leaks. */
volatile size_t huge = (size_t)-1;
setvbuf(stdout, NULL, _IONBF, 0);
puts("lost_realloc: realloc failure overwrites the only pointer to the buffer");
array.size = 0;
array.capacity = 160;
array.data = malloc(array.capacity * sizeof *array.data);
if (array.data == NULL) {
fputs("out of memory\n", stderr);
return EXIT_FAILURE;
}
for (index = 0; index < array.capacity; ++index) {
if (!array_push(&array, (int)index)) {
fputs("push failed\n", stderr);
return EXIT_FAILURE;
}
}
printf("buffer: %zu slots, %zu bytes\n", array.capacity,
array.capacity * sizeof *array.data);
puts("asking realloc for an impossible size and writing the result to array.data");
array.data = realloc(array.data, huge); /* on failure the old block is lost */
if (array.data == NULL)
puts("lost_realloc: realloc failed, the original buffer is leaked");
return EXIT_SUCCESS;
}
Output:
lost_realloc: realloc failure overwrites the only pointer to the buffer
buffer: 160 slots, 640 bytes
asking realloc for an impossible size and writing the result to array.data
lost_realloc: realloc failed, the original buffer is leaked
Output (summarized from the LeakSanitizer report):
LeakSanitizer: detected memory leaks
Direct leak of 640 byte(s) in 1 object(s) allocated by main at pitfalls/lost_realloc.c:68
SUMMARY: LeakSanitizer: 640 byte(s) leaked in 1 allocation(s).
The push assigns the result of realloc straight back to the array’s only pointer. When the request fails, realloc returns NULL, the pointer is overwritten, and the old 640-byte buffer is unreachable. LeakSanitizer reports a direct leak of 640 bytes. The failed request in the demo is deliberately impossible (SIZE_MAX bytes), which makes the failure deterministic. The fix is the temporary pointer the article’s array_grow uses: on NULL the array is unchanged and the caller gets false.
5. Freeing the Buffer Twice
static void array_destroy_broken(IntArray *array)
{
free(array->data);
}
/* The ordinary clear: release the buffer and reset the structure. */
static void array_clear(IntArray *array)
{
free(array->data);
array->data = NULL;
array->size = 0;
array->capacity = 0;
}
int main(void)
{
IntArray array;
size_t index;
setvbuf(stdout, NULL, _IONBF, 0);
puts("double_free: destroy frees the buffer and clear frees it again");
array.data = malloc(4 * sizeof *array.data);
if (array.data == NULL) {
fputs("out of memory\n", stderr);
return EXIT_FAILURE;
}
array.size = 0;
array.capacity = 4;
for (index = 0; index < 3; ++index) {
if (!array_push(&array, (int)(10 * (index + 1)))) {
fputs("push failed\n", stderr);
return EXIT_FAILURE;
}
}
array_destroy_broken(&array);
puts("destroy freed the 4-slot buffer and left the pointer set");
puts("clear frees the same pointer again");
array_clear(&array); /* double-free: the block is already gone */
printf("clear returned, size %zu, capacity %zu\n", array.size,
array.capacity);
return EXIT_SUCCESS;
}
Output:
double_free: destroy frees the buffer and clear frees it again
destroy freed the 4-slot buffer and left the pointer set
clear frees the same pointer again
Output (summarized from the AddressSanitizer report):
AddressSanitizer: attempting double-free
free at pitfalls/double_free.c:31 (array_clear) after the earlier free at pitfalls/double_free.c:25 (array_destroy_broken)
16-byte region allocated by malloc at pitfalls/double_free.c:60 (main)
SUMMARY: AddressSanitizer: double-free in free, called from array_clear
The destroy function frees the buffer but does not reset the pointer, and clear is implemented as free(data) again. AddressSanitizer reports a double-free on the second call, with the earlier free named in the report. The fix is one assignment: a freed array’s data is NULL and its capacity is 0, so a second free is a no-op instead of undefined behavior.
Key Takeaways
- A dynamic array is a heap buffer plus a size and a capacity. The invariant is
size <= capacity, and a growth may move every value to a new buffer. - Geometric growth makes appends amortized O(1): doubling copies at most about 2n elements over n appends, 1.5 about 3n, 1.25 about 5n.
- The measured run: 17 reallocations over 4.2 MB of old buffers for doubling, 29 over 8.0 MB for 1.5, and none for the reserve baseline.
- Popping lowers size but not capacity. The buffer keeps its slots until
shrink_to_fit, which costs one more reallocation. - Never overwrite the only pointer with the
reallocreturn value. Use a temporary, and leave the array unchanged on failure. - After
reallocthe old pointer is invalid even when the values were copied, so an alias to it is a use-after-free. reserveis grow-only andshrink_to_fitis the explicit shrink, matchingstd::vectorand the other standard libraries.
Conclusion
A dynamic array is the smallest data structure with a real allocation policy, and the policy is most of the design. The size and capacity pair, the temporary pointer in the growth path, the explicit shrink and the careful use of realloc are what separate a vector that survives from one that passes a quick test. The measurements give the trade-off concrete numbers. Doubling reallocated 17 times over 4.2 MB of old buffers but could leave half the buffer empty after a growth, while 1.5 reallocated 29 times over 8.0 MB with a one-third bound. The churn run showed 3.8 MB held for a 100,000-value array until shrink_to_fit released it.
The types of data structures guide places the array beside the linked structures it competes with, and the data structures hub lists the whole series. In C++, use the standard library’s vector, reserve when the size is known, and shrink only when the memory matters. In C, where there is no standard vector, write this one and keep the old pointer rule in mind.
Source Code and Tests
The programs on this page are in the data-structures/dynamic-array-in-c directory of the c-examples repository:
| Language | Repository directory | Build status |
|---|---|---|
| C | mycplus/c-examples: data-structures/dynamic-array-in-c |
The example builds and tests with CMake:
cmake -S . -B build
cmake --build build
ctest --test-dir build --output-on-failure
What the builds check. The demo’s stdout is compared byte for byte with tests/expected/ordered.txt. The tests compare every operation against a fixed model array over 100,000 random push/pop/set/get/reserve operations, check the growth sequence and the size/capacity invariant after every batch, exercise the failure path with an impossible reserve request, and cover clear, empty pop and bounds checks. The Linux workflow also runs the tests, demo and pitfall programs under AddressSanitizer and UndefinedBehaviorSanitizer, with LeakSanitizer checking the lost-pointer pitfall. The builds do not check the growth or churn timing columns, which belong to one machine and are captured with the article.
What I Verified
The example directory contains the test program and the captured runs, and the table states which system ran each check.
| Check | Ubuntu 24.04 (WSL2) | Windows 11 (MSVC) |
|---|---|---|
| Build and tests, C, GCC 13.3 C11 and C17 | Pass (3 of 3 tests) | Not applicable |
| Build and tests, C, Clang 18.1.3 C11 and C17 | Pass (3 of 3 tests) | Not applicable |
Build and tests, C, MSVC 19.44 /W4 /WX | Not applicable | Pass (3 of 3 tests) |
| AddressSanitizer and UndefinedBehaviorSanitizer, tests, demo and five pitfalls | Pass (3 of 3 tests) | Not applicable |
| Five pitfalls, each caught by the check named in its section | Pass (4 ASan checks, 1 LSan check) | Not applicable |
| Growth and churn experiments | Run on Ubuntu 24.04, output in the sections above | Not run |
Not covered: 32-bit builds, compilers newer than GCC 13.3 and Clang 18.1.3, macOS, other growth factors beyond the three measured, custom allocators, and timings on any other machine.




