A hard and fast C array is allotted as soon as and by no means adjustments dimension. A dynamic array retains a buffer, a rely of used parts and a rely of allotted slots, and when the buffer fills it asks realloc for a much bigger one. Within the experiment beneath, a million appends beneath a doubling coverage prompted 17 reallocations that might have copied as much as 4.2 MB of outdated buffers, and the 1.5 coverage prompted 29 reallocations and as much as 8.0 MB. The copies are amortized work, not per-push work, and the expansion issue decides how usually they occur and the way a lot reminiscence the array holds in reserve.
This information implements a growable int vector in C: the construction, the expansion coverage, realloc failure dealing with, reserve and shrink_to_fit, and 5 pointer errors that realloc invitations, every caught by a sanitizer. The Arrays article covers mounted arrays and reminiscence structure, and the std::vector information covers the C++ container this code is modeled on. This text focuses on writing the vector your self in C. The code was constructed and examined on Ubuntu 24.04 beneath WSL2 with GCC and Clang and on Home windows 11 with MSVC, and each output block beneath comes from an actual run.
What Is a Dynamic Array?
A dynamic array is an array that owns a heap buffer and grows it on demand. It retains a dimension for the values in use and a capability for the slots allotted, and when a push finds dimension equal to capability it strikes the values into a bigger buffer and continues. The end result retains O(1) indexing and amortized O(1) appends whereas the capability follows the demand.
The 2 numbers are the entire design. dimension says what number of values are alive and is what the caller sees, whereas capability says what number of slots the buffer has and is invisible besides by means of efficiency and reminiscence use. The invariant is dimension <= capability, and each operation preserves it. Indexing is information[i] after a bounds verify, which is O(1) and as cache-friendly because the mounted array it replaces. Appending is O(1) more often than not and O(capability) when the buffer should develop, and the expansion is chosen in order that the costly case is uncommon sufficient to common out.
The basic amortized argument says why the coverage issues. If the capability doubles when full, the copies over n appends complete at most 2n parts, so the typical copy per append is a continuing despite the fact that particular person appends can copy the entire array. Development elements beneath 2 copy extra in complete however maintain the spare reminiscence smaller, and elements above 2 copy much less however waste extra slots. That trade-off is precisely what the expansion experiment measures, and the waste is just not free in a program that holds many small arrays.
The cache habits is price stating individually. A contiguous buffer provides the CPU a prefetch-friendly stroll and a single allocation, whereas pointer-linked constructions will pay a cache miss per factor. The expansion copy is the value paid for that structure, and it’s paid not often.
The options clarify the area of interest. A hard and fast array can not develop. A linked listing grows in O(1) however loses indexing and cache locality. A block-based container, akin to a deque, grows on the ends with out copying every thing however is just not one contiguous buffer. A dynamic array is the correct default when indexing, iteration and a compact buffer matter and appends dominate, which is why std::vector, Java’s ArrayList, C#’s Checklist<T> and Python’s listing all use a growable contiguous buffer.
How This Was Measured
| Setting | Worth |
|---|---|
| Date examined | December 1, 2026 |
| {Hardware} | Intel Core i7-8700K, 6 cores and 12 threads at 3.70 GHz, 32 GB RAM, Home windows 11 Schooling construct 26300 |
| Working system | Ubuntu 24.04.5 beneath WSL2, kernel 5.15.146.1-microsoft-standard-WSL2, glibc 2.39; Home windows 11 for the MSVC construct |
| Compilers | GCC 13.3 and Clang 18.1.3 at -O2 by means of CMake Launch; MSVC 19.44 at /W4 /WX |
| Development experiment | 1,000,000 int appends from an preliminary capability of 8, for progress elements 2, 1.5 and 1.25, plus a reserve-exact baseline |
| Churn experiment | 1,000,000 appends adopted by 900,000 pops, then shrink_to_fit |
| What’s timed | The append loop per coverage. The experiment tracks capacities and duplicate volumes itself with malloc/realloc and the identical progress guidelines because the article’s code |
| Statistic | Single run per coverage, milliseconds. Capacities, reallocation counts and copied bytes are deterministic |
| Examine | Each coverage should finish with the identical values and checksum, and the churn run should maintain the identical remaining values earlier than and after shrinking |
No CPU pinning or frequency scaling management was used, and the host runs different software program, so the instances are indicative for this machine and the counts are the reproducible half. All numbers come from one machine and one WSL2 occasion.
The Development Coverage: Reallocations, Copies and Waste
The shipped array doubles: new_capacity = capability == 0 ? 8 : capability * 2, with an overflow guard for capacities close to SIZE_MAX. A push that finds the buffer full calls realloc for the brand new capability and shops the lead to a brief pointer. realloc both extends the block in place or allocates a brand new one, copies the values and frees the outdated one. The non permanent is the entire security story: if realloc returns NULL, the outdated pointer remains to be legitimate, the array is unchanged, and the push reviews failure as a substitute of shedding the buffer.
The experiment runs every coverage by itself small vector somewhat than the article’s IntArray, so the capability sequence and the copy quantity are express. Its copied-bytes column counts the outdated buffer at each reallocation, which is what realloc should copy when it can not prolong the block in place. The reserve baseline calls malloc as soon as after which pushes with none progress, which is why its column is zero.
The expansion issue is a coverage, not a regulation. Doubling provides the fewest reallocations and the biggest jumps, 1.5 provides extra reallocations and smaller jumps, and 1.25 extra and smaller nonetheless.
The copies over n appends are a geometrical sequence, so the issue adjustments the fixed: doubling copies at most about 2n parts in complete, 1.5 about 3n, and 1.25 about 5n. The waste proper after a progress is (issue - 1) * old_capacity, so doubling can maintain as much as half its slots empty and 1.5 as much as a 3rd. The ultimate waste at a selected n additionally relies on the place n falls between two progress factors, which is why the desk contains the height waste in addition to the ultimate waste.
Why Not realloc on Each Push?
The primary design query is why not name realloc for each push and skip the capability coverage. The reply is the copied bytes. If each append reallocates to precisely dimension + 1 and each realloc has to maneuver the block, the millionth push copies about 4 MB and the whole is close to 2 TB. That’s quadratic within the variety of appends. An allocator that may usually prolong a block in place hides a number of the value, however nothing within the C normal guarantees it, and each name nonetheless pays for the allocator itself.
The experiment’s reserve baseline reveals the opposite excessive: one allocation of precisely a million slots, zero reallocations and nil bytes copied in the course of the progress section, at the price of holding the ultimate capability from the beginning. The capability coverage sits between these extremes and trades copying towards spare reminiscence, and the geometric sequence is what turns the worst case into an amortized fixed.
The identical arithmetic explains why the coverage belongs contained in the container somewhat than within the caller. A caller that pushes in a loop can not know when the buffer will fill, and a caller that reserves precisely the ultimate dimension has to know that dimension upfront. The container is aware of each the present dimension and the present capability, so it’s the solely layer that may make the commerce on each push. That can also be why the usual containers expose reserve as a touch somewhat than a requirement.
Dynamic Array Implementation in C
The construction is three fields and a set of features that maintain them constant. The article’s code places the entire kind in src/darray.c so the demo could be a single translation unit, and the assessments embrace the identical file with important renamed, which is the repository’s conference for testing static helpers straight.
static bool array_grow(IntArray *array)
{
size_t new_capacity;
int *new_data;
if (array->capability == 0) {
new_capacity = (size_t)ARRAY_MIN_CAPACITY;
} else {
if (array->capability > SIZE_MAX / 2)
return false;
new_capacity = array->capability * 2;
}
if (new_capacity > SIZE_MAX / sizeof *new_data)
return false;
new_data = realloc(array->information, new_capacity * sizeof *new_data);
if (new_data == NULL)
return false;
array->information = new_data;
array->capability = new_capacity;
return true;
}
bool array_push(IntArray *array, int worth)
{
if (array->dimension == array->capability && !array_grow(array))
return false;
array->information[array->size] = worth;
array->dimension++;
return true;
}
bool array_reserve(IntArray *array, size_t new_capacity)
{
int *new_data;
if (new_capacity <= array->capability)
return true;
if (new_capacity > SIZE_MAX / sizeof *new_data)
return false;
new_data = realloc(array->information, new_capacity * sizeof *new_data);
if (new_data == NULL)
return false;
array->information = new_data;
array->capability = new_capacity;
return true;
}
/* Reallocates to precisely dimension slots. An empty array frees the buffer and resets
* the capability to 0. Returns false on allocation failure, after which the array is
* unchanged. */
bool array_shrink_to_fit(IntArray *array)
{
int *new_data;
if (array->dimension == 0) {
free(array->information);
array->information = NULL;
array->capability = 0;
return true;
}
if (array->capability == array->dimension)
return true;
new_data = realloc(array->information, array->dimension * sizeof *new_data);
if (new_data == NULL)
return false;
array->information = new_data;
array->capability = array->dimension;
return true;
}
array_push is the one perform that grows the buffer, and array_reserve is the one different path to a bigger allocation. reserve is grow-only, like std::vector::reserve: asking for a capability the array already has adjustments nothing, even when the request is smaller than the present dimension. That asymmetry is deliberate, as a result of shrink_to_fit is the one operation that lowers the capability, and it’s express as a result of it prices a reallocation and a replica.
Output:
dynamic int array, preliminary capability 2
push 10, 20 -> dimension 2, capability 2
push 30 -> dimension 3, capability 4
values: 10 20 30
get 1 -> 20, get 3 -> out of vary
set 1 to 25 -> values: 10 25 30
pop -> 30, dimension 2, capability 4
reserve 10 -> dimension 2, capability 10
shrink_to_fit -> dimension 2, capability 2
clear -> dimension 0, capability 2
The Price of Rising: Measured
The expansion experiment pushes a million ints beneath every coverage and data what the expansion did: what number of reallocations occurred, what number of bytes the outdated buffers held after they had been copied, the ultimate capability, the ultimate waste and the biggest waste seen instantly after a progress.
static size_t next_capacity(size_t capability, unsigned numerator,
unsigned denominator)
{
size_t grown = (capability / denominator) * numerator
+ (capability % denominator) * numerator / denominator;
if (grown <= capability)
grown = capability + 1;
return grown;
}
static void grow_vec_push(GrowVec *vector, int worth, unsigned numerator,
unsigned denominator)
{
if (vector->dimension == vector->capability) {
size_t old_capacity = vector->capability;
size_t new_capacity = next_capacity(old_capacity, numerator, denominator);
int *new_data;
if (new_capacity > SIZE_MAX / sizeof *new_data)
fail("capability overflow");
new_data = realloc(vector->information, new_capacity * sizeof *new_data);
if (new_data == NULL)
fail("out of reminiscence");
vector->information = new_data;
vector->capability = new_capacity;
vector->reallocations++;
vector->bytes_copied += old_capacity * sizeof *new_data;
if (new_capacity - vector->dimension > vector->peak_wasted)
vector->peak_wasted = new_capacity - vector->dimension;
}
vector->information[vector->size] = worth;
vector->dimension++;
}
/* The reserve-exact baseline: one allocation of the requested capability earlier than
* the append loop. It isn't a progress, so no counter strikes. */
static void grow_vec_reserve(GrowVec *vector, size_t capability)
{
int *new_data;
if (capability <= vector->capability)
return;
if (capability > SIZE_MAX / sizeof *new_data)
fail("reserve capability overflow");
new_data = realloc(vector->information, capability * sizeof *new_data);
if (new_data == NULL)
fail("out of reminiscence");
vector->information = new_data;
vector->capability = capability;
}
Output:
1,000,000 int appends, preliminary capability 8
coverage reallocations bytes_copied final_capacity wasted_slots peak_wasted time_ms
develop x2 17 4194272 1048576 48576 524288 2.704
develop x1.5 29 8042468 1005310 5310 335103 2.022
develop x1.25 54 17956076 1122241 122241 224448 1.230
reserve actual 0 0 1000000 0 0 1.610
The columns to learn usually are not the milliseconds. Doubling reallocated 17 instances over outdated buffers totaling 4,194,272 bytes (about 4.2 MB), 1.5 reallocated 29 instances over 8,042,468 bytes (8.0 MB), and 1.25 reallocated 54 instances over 17,956,076 bytes (18.0 MB). The reserve baseline prompted no reallocation and no copies in any respect.
The height waste column is the structural distinction: 524,288 spare slots instantly after a doubling, 50% of the capability, towards 335,103 (33%) for 1.5 and 224,448 (20%) for 1.25, which is the (issue – 1) certain in apply. The ultimate waste is noisier. This run ended with 48,576 spare slots beneath doubling (4.6%), 5,310 beneath 1.5 (0.5%) and 122,241 beneath 1.25 (10.9%), as a result of the ultimate capability relies on the place a million lands between two progress factors. The instances, 1.2 to 2.7 ms, are sufficiently small that allocator habits and noise dominate them, so the counts and bytes are the end result.
Reminiscence Retained After Popping
Popping values lowers dimension however by no means lowers capability: the buffer retains its slots, which is the purpose of an array that might be crammed once more. The churn experiment appends one million values, pops 9 hundred thousand, after which calls shrink_to_fit to point out what the capability prices earlier than and after the specific launch.
static void vec_grow(IntVec *vector)
{
size_t new_capacity = vector->capability == 0 ? (size_t)MIN_CAPACITY
: vector->capability * 2;
int *new_data;
if (new_capacity > SIZE_MAX / sizeof *new_data)
fail("capability overflow");
new_data = realloc(vector->information, new_capacity * sizeof *new_data);
if (new_data == NULL)
fail("out of reminiscence");
vector->information = new_data;
vector->capability = new_capacity;
}
static void vec_shrink_to_fit(IntVec *vector)
{
int *new_data;
if (vector->dimension == 0) {
free(vector->information);
vector->information = NULL;
vector->capability = 0;
return;
}
if (vector->capability == vector->dimension)
return;
new_data = realloc(vector->information, vector->dimension * sizeof *new_data);
if (new_data == NULL)
fail("shrink_to_fit failed");
vector->information = new_data;
vector->capability = vector->dimension;
}
Output:
1,000,000 appends then 900,000 pops
stage dimension capability resident_bytes
after appends 1000000 1048576 4194304
after pops 100000 1048576 4194304
after shrink_to_fit 100000 100000 400000
checksum: 9259950532764359811
After one million appends the array held 1,048,576 slots, 4,194,304 bytes, for 1,000,000 values. Popping 900,000 values decreased the dimensions to 100,000 however left each slot allotted, so the buffer nonetheless held 4,194,304 bytes. shrink_to_fit reallocated to precisely 100,000 slots, 400,000 bytes, and launched 3,794,304 bytes (3.8 MB), with the remaining values and the checksum unchanged.
The fee is one reallocation and at most one copy of the reside values, so doing it as soon as after a burst is cheaper than shrinking after each pop. That’s the commerce the kind gives: capability is stored for the subsequent burst of appends, and this system decides when the reminiscence is price greater than the longer term writes.
The Failure Path and the Overflow Guard
The completely happy path is the copy, and the failure path is what makes the kind protected. realloc returns NULL when the request can’t be glad and leaves the outdated block untouched, so the array should solely swap buffers after checking the end result. The expansion helper does precisely that: it computes the brand new capability, calls realloc into a brief pointer, returns false on NULL, and solely then updates information and capability. The push propagates the false to its caller and the array stays legitimate, which the assessments train with an not possible reserve request that should go away the array unchanged.
The second guard is arithmetic. Doubling multiplies a size_t by two, and a capability above SIZE_MAX / 2 wraps round, and a wrapped worth might be smaller than the present dimension, which might make the subsequent realloc shrink the buffer and the subsequent push write previous its finish. The expansion helper checks the capability certain and the byte-size multiplication earlier than allocating, and the assessments drive the byte-size guard with reserve and init requests simply previous SIZE_MAX / sizeof(int). Neither guard prices something measurable within the append loop, and each are the distinction between a failure that reviews an error and a failure that corrupts reminiscence silently.
The place the Different Languages Land
The identical design seems in each normal library, with completely different insurance policies and names. This text implements the C model, and the others are listed so the identical trade-offs might be acknowledged when utilizing them.
| Language | Container | Development coverage | Reserve | Shrink |
|---|---|---|---|---|
| C | this text | 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 instances | ensureCapacity, grow-only |
trimToSize |
| C# | Checklist<T> |
doubles | Capability / EnsureCapacity |
TrimExcess |
| Python | listing |
over-allocates geometrically | none uncovered | none |
The expansion elements are implementation particulars somewhat than legal guidelines: Java’s ArrayList has used about 1.5 since early variations and the C++ normal says solely that std::vector grows geometrically, so the precise capability soar can change between library variations. Python’s listing over-allocates however exposes no capability, which is why reserve doesn’t seem in its row. The C++ container is described within the cppreference std::vector web page, Java’s within the ArrayList documentation, Python’s listing within the information constructions tutorial, and C#’s within the Checklist<T> documentation. The C realloc semantics this code relies on are on cppreference as effectively.
When a Dynamic Array Is the Incorrect Alternative
The array wins when the values are contiguous, listed and appended in bulk. It loses when the workload inserts or deletes within the center repeatedly: each operation strikes the tail, which is O(n), and no progress coverage adjustments that. A linked listing retains these operations O(1) when the node is held, at the price of further pointers per worth, scattered nodes on each stroll and no indexing. That’s the commerce the doubly linked listing article measures. A block-based container akin to a deque retains O(1) operations at each ends and avoids one big copy, however center insertions nonetheless transfer information and indexing provides a degree of indirection.
The array additionally loses when this system holds many small arrays that develop unpredictably: the spare capability of every is reminiscence held towards a future progress which will by no means come, which is why reserving or shrinking to the anticipated dimension issues greater than the expansion think about that regime. When the utmost dimension is thought and stuck, a plain array and a rely is easier than any growable kind. The dynamic array is a default, not a common reply, and the associated fee it trades away is the flexibility to maneuver values cheaply.
5 Methods a Dynamic Array Passes a Fast Take a look at and Nonetheless Fails
Every of those applications compiles cleanly with -Wall -Wextra -pedantic and prints one thing believable till the road beneath it, or till a sanitizer stops it. The workflows re-run every and assert the road or the sanitizer abstract.
1. The Alias That Outlives realloc
static bool array_push(IntArray *array, int worth)
{
if (array->dimension == array->capability) {
size_t new_capacity = array->capability == 0 ? 8 : array->capability * 2;
int *new_data = realloc(array->information, new_capacity * sizeof *new_data);
if (new_data == NULL)
return false;
array->information = new_data;
array->capability = new_capacity;
}
array->information[array->size] = worth;
array->dimension++;
return true;
}
int important(void)
{
IntArray array;
int *alias;
size_t index;
setvbuf(stdout, NULL, _IONBF, 0);
places("dangling_alias: an alias to the outdated buffer is used after the push grows it");
array.information = malloc(4 * sizeof *array.information);
if (array.information == NULL) {
fputs("out of memoryn", stderr);
return EXIT_FAILURE;
}
array.dimension = 0;
array.capability = 4;
for (index = 0; index < 4; ++index) {
if (!array_push(&array, (int)(10 * (index + 1)))) {
fputs("push failedn", stderr);
return EXIT_FAILURE;
}
}
alias = array.information;
printf("capability %zu: alias saved the tackle of the 4-slot buffern",
array.capability);
if (!array_push(&array, 50)) {
fputs("push failedn", stderr);
return EXIT_FAILURE;
}
printf("push 50 grew capability to %zu: realloc moved the buffern",
array.capability);
places("writing alias[0] = 99 by means of the stale pointer");
alias[0] = 99; /* heap-use-after-free: the outdated buffer is gone */
printf("alias[0] = %d, dimension %zun", alias[0], array.dimension);
free(array.information);
return EXIT_SUCCESS;
}
Output:
dangling_alias: an alias to the outdated buffer is used after the push grows it
capability 4: alias saved the tackle of the 4-slot buffer
push 50 grew capability to eight: realloc moved the buffer
writing alias[0] = 99 by means of the stale pointer
Output (summarized from the AddressSanitizer report):
AddressSanitizer: heap-use-after-free
WRITE of dimension 4 at pitfalls/dangling_alias.c:70 (important)
16-byte area freed by realloc at pitfalls/dangling_alias.c:27 (array_push)
16-byte area beforehand allotted by malloc at pitfalls/dangling_alias.c:47 (important)
SUMMARY: AddressSanitizer: heap-use-after-free pitfalls/dangling_alias.c:70 in important
The push perform itself handles progress accurately with a brief realloc pointer, however important retains an alias to the outdated buffer throughout the push. The push grows the array, realloc strikes it, and the alias now factors at freed reminiscence. AddressSanitizer reviews a heap-use-after-free on the write, with the freed area recognized because the outdated buffer inside array_push. Below AddressSanitizer realloc at all times strikes the block, so the bug reveals on each run, whereas a traditional construct fails solely when the allocator occurs to maneuver it. The array by no means knew concerning the alias, which is why inside pointers right into a growable buffer are unsafe throughout any operation that may develop it.
2. clear That Forgets to Reset
static bool array_push(IntArray *array, int worth)
{
if (array->dimension == array->capability) {
size_t new_capacity = array->capability == 0 ? 8 : array->capability * 2;
int *new_data = realloc(array->information, new_capacity * sizeof *new_data);
if (new_data == NULL)
return false;
array->information = new_data;
array->capability = new_capacity;
}
array->information[array->size] = worth;
array->dimension++;
return true;
}
/* The bug: the buffer is freed, however the array nonetheless claims the outdated dimension and
* capability. The information pointer is just not reset both. */
static void array_clear_broken(IntArray *array)
{
free(array->information);
}
Output:
clear_without_reset: clear frees the buffer however leaves dimension and capability
clear freed the buffer and left dimension 3, capability 4
push 40 writes information[3] by means of the freed buffer
Output (summarized from the AddressSanitizer report):
AddressSanitizer: heap-use-after-free
WRITE of dimension 4 at pitfalls/clear_without_reset.c:33 (array_push)
16-byte area freed by free at pitfalls/clear_without_reset.c:42 (array_clear_broken)
16-byte area beforehand allotted by malloc at pitfalls/clear_without_reset.c:52 (important)
SUMMARY: AddressSanitizer: heap-use-after-free pitfalls/clear_without_reset.c:33 in array_push
The damaged clear frees the buffer and leaves dimension and capability untouched, which seems to be fantastic till the subsequent push. The array believes it nonetheless has capability, writes at information[size], and AddressSanitizer reviews a heap-use-after-free on the freed 16-byte buffer. The proper clear units dimension to 0 and retains the buffer, whereas a destroy frees it and resets the pointer, dimension and capability collectively.
3. A Push With out a Development Examine
static bool array_push_broken(IntArray *array, int worth)
{
array->information[array->size] = worth;
array->dimension++;
return true;
}
int important(void)
{
IntArray array;
size_t index;
setvbuf(stdout, NULL, _IONBF, 0);
places("push_without_grow: push writes information[size] when the buffer is full");
array.dimension = 0;
array.capability = 8;
array.information = malloc(array.capability * sizeof *array.information);
if (array.information == NULL) {
fputs("out of memoryn", stderr);
return EXIT_FAILURE;
}
for (index = 0; index < array.capability; ++index)
(void)array_push_broken(&array, (int)(10 * (index + 1)));
printf("dimension %zu, capability %zu: the buffer has no spare slotn", array.dimension,
array.capability);
places("push 90 writes information[8] one slot previous the tip of the 8-slot buffer");
(void)array_push_broken(&array, 90);
printf("push 90 reported success, dimension %zun", array.dimension);
free(array.information);
return EXIT_SUCCESS;
}
Output:
push_without_grow: push writes information[size] when the buffer is full
dimension 8, capability 8: the buffer has no spare slot
push 90 writes information[8] one slot previous the tip of the 8-slot buffer
Output (summarized from the AddressSanitizer report):
AddressSanitizer: heap-buffer-overflow
WRITE of dimension 4 at pitfalls/push_without_grow.c:24 (array_push_broken)
32-byte area allotted by malloc at pitfalls/push_without_grow.c:38 (important)
SUMMARY: AddressSanitizer: heap-buffer-overflow pitfalls/push_without_grow.c:24 in array_push_broken
The push writes at information[size] with out checking whether or not dimension has reached capability. Eight values fill the 32-byte buffer, push 90 writes information[8] one slot previous the tip, and AddressSanitizer reviews a heap-buffer-overflow on the write. The lesson is the invariant, not the verify: each push should both have already got room or develop, and a take a look at that solely pushes throughout the preliminary capability by no means sees the bug.
4. Shedding the Outdated Pointer When realloc Fails
static bool array_push(IntArray *array, int worth)
{
if (array->dimension == array->capability) {
size_t new_capacity = array->capability == 0 ? 8 : array->capability * 2;
int *new_data = realloc(array->information, new_capacity * sizeof *new_data);
if (new_data == NULL)
return false;
array->information = new_data;
array->capability = new_capacity;
}
array->information[array->size] = worth;
array->dimension++;
return true;
}
int important(void)
{
IntArray array;
size_t index;
/* risky retains the compiler from proving the request not possible at
* compile time, so the failure occurs in realloc at run time, the place the
* misplaced pointer leaks. */
risky size_t big = (size_t)-1;
setvbuf(stdout, NULL, _IONBF, 0);
places("lost_realloc: realloc failure overwrites the one pointer to the buffer");
array.dimension = 0;
array.capability = 160;
array.information = malloc(array.capability * sizeof *array.information);
if (array.information == NULL) {
fputs("out of memoryn", stderr);
return EXIT_FAILURE;
}
for (index = 0; index < array.capability; ++index) {
if (!array_push(&array, (int)index)) {
fputs("push failedn", stderr);
return EXIT_FAILURE;
}
}
printf("buffer: %zu slots, %zu bytesn", array.capability,
array.capability * sizeof *array.information);
places("asking realloc for an not possible dimension and writing the end result to array.information");
array.information = realloc(array.information, big); /* on failure the outdated block is misplaced */
if (array.information == NULL)
places("lost_realloc: realloc failed, the unique buffer is leaked");
return EXIT_SUCCESS;
}
Output:
lost_realloc: realloc failure overwrites the one pointer to the buffer
buffer: 160 slots, 640 bytes
asking realloc for an not possible dimension and writing the end result to array.information
lost_realloc: realloc failed, the unique buffer is leaked
Output (summarized from the LeakSanitizer report):
LeakSanitizer: detected reminiscence leaks
Direct leak of 640 byte(s) in 1 object(s) allotted by important at pitfalls/lost_realloc.c:68
SUMMARY: LeakSanitizer: 640 byte(s) leaked in 1 allocation(s).
The push assigns the results of realloc straight again to the array’s solely pointer. When the request fails, realloc returns NULL, the pointer is overwritten, and the outdated 640-byte buffer is unreachable. LeakSanitizer reviews a direct leak of 640 bytes. The failed request within the demo is intentionally not possible (SIZE_MAX bytes), which makes the failure deterministic. The repair is the non permanent pointer the article’s array_grow makes use of: on NULL the array is unchanged and the caller will get false.
5. Releasing the Buffer Twice
static void array_destroy_broken(IntArray *array)
{
free(array->information);
}
/* The atypical clear: launch the buffer and reset the construction. */
static void array_clear(IntArray *array)
{
free(array->information);
array->information = NULL;
array->dimension = 0;
array->capability = 0;
}
int important(void)
{
IntArray array;
size_t index;
setvbuf(stdout, NULL, _IONBF, 0);
places("double_free: destroy frees the buffer and clear frees it once more");
array.information = malloc(4 * sizeof *array.information);
if (array.information == NULL) {
fputs("out of memoryn", stderr);
return EXIT_FAILURE;
}
array.dimension = 0;
array.capability = 4;
for (index = 0; index < 3; ++index) {
if (!array_push(&array, (int)(10 * (index + 1)))) {
fputs("push failedn", stderr);
return EXIT_FAILURE;
}
}
array_destroy_broken(&array);
places("destroy freed the 4-slot buffer and left the pointer set");
places("clear frees the identical pointer once more");
array_clear(&array); /* double-free: the block is already gone */
printf("clear returned, dimension %zu, capability %zun", array.dimension,
array.capability);
return EXIT_SUCCESS;
}
Output:
double_free: destroy frees the buffer and clear frees it once more
destroy freed the 4-slot buffer and left the pointer set
clear frees the identical pointer once more
Output (summarized from the AddressSanitizer report):
AddressSanitizer: trying double-free
free at pitfalls/double_free.c:31 (array_clear) after the sooner free at pitfalls/double_free.c:25 (array_destroy_broken)
16-byte area allotted by malloc at pitfalls/double_free.c:60 (important)
SUMMARY: AddressSanitizer: double-free in free, referred to as from array_clear
The destroy perform frees the buffer however doesn’t reset the pointer, and clear is carried out as free(information) once more. AddressSanitizer reviews a double-free on the second name, with the sooner free named within the report. The repair is one project: a freed array’s information is NULL and its capability is 0, so a second free is a no-op as a substitute of undefined habits.
Key Takeaways
- A dynamic array is a heap buffer plus a dimension and a capability. The invariant is
dimension <= capability, and a progress could transfer each worth to a brand new buffer. - Geometric progress makes appends amortized O(1): doubling copies at most about 2n parts over n appends, 1.5 about 3n, 1.25 about 5n.
- The measured run: 17 reallocations over 4.2 MB of outdated buffers for doubling, 29 over 8.0 MB for 1.5, and none for the reserve baseline.
- Popping lowers dimension however not capability. The buffer retains its slots till
shrink_to_fit, which prices another reallocation. - By no means overwrite the one pointer with the
reallocreturn worth. Use a brief, and go away the array unchanged on failure. - After
reallocthe outdated pointer is invalid even when the values had been copied, so an alias to it’s a use-after-free. reserveis grow-only andshrink_to_fitis the specific shrink, matchingstd::vectorand the opposite normal libraries.
Conclusion
A dynamic array is the smallest information construction with an actual allocation coverage, and the coverage is a lot of the design. The scale and capability pair, the non permanent pointer within the progress path, the specific shrink and the cautious use of realloc are what separate a vector that survives from one which passes a fast take a look at. The measurements give the trade-off concrete numbers. Doubling reallocated 17 instances over 4.2 MB of outdated buffers however might go away half the buffer empty after a progress, whereas 1.5 reallocated 29 instances over 8.0 MB with a one-third certain. The churn run confirmed 3.8 MB held for a 100,000-value array till shrink_to_fit launched it.
The forms of information constructions information locations the array beside the linked constructions it competes with, and the information constructions hub lists the entire sequence. In C++, use the usual library’s vector, reserve when the dimensions is thought, and shrink solely when the reminiscence issues. In C, the place there isn’t a normal vector, write this one and maintain the outdated pointer rule in thoughts.
Supply Code and Exams
The applications on this web page are within the data-structures/dynamic-array-in-c listing of the c-examples repository:
The instance builds and assessments with CMake:
cmake -S . -B construct
cmake --build construct
ctest --test-dir construct --output-on-failure
What the builds verify. The demo’s stdout is in contrast byte for byte with assessments/anticipated/ordered.txt. The assessments evaluate each operation towards a set mannequin array over 100,000 random push/pop/set/get/reserve operations, verify the expansion sequence and the dimensions/capability invariant after each batch, train the failure path with an not possible reserve request, and canopy clear, empty pop and bounds checks. The Linux workflow additionally runs the assessments, demo and pitfall applications beneath AddressSanitizer and UndefinedBehaviorSanitizer, with LeakSanitizer checking the lost-pointer pitfall. The builds don’t verify the expansion or churn timing columns, which belong to at least one machine and are captured with the article.
What I Verified
The instance listing incorporates the take a look at program and the captured runs, and the desk states which system ran every verify.
| Examine | Ubuntu 24.04 (WSL2) | Home windows 11 (MSVC) |
|---|---|---|
| Construct and assessments, C, GCC 13.3 C11 and C17 | Go (3 of three assessments) | Not relevant |
| Construct and assessments, C, Clang 18.1.3 C11 and C17 | Go (3 of three assessments) | Not relevant |
Construct and assessments, C, MSVC 19.44 /W4 /WX |
Not relevant | Go (3 of three assessments) |
| AddressSanitizer and UndefinedBehaviorSanitizer, assessments, demo and 5 pitfalls | Go (3 of three assessments) | Not relevant |
| 5 pitfalls, every caught by the verify named in its part | Go (4 ASan checks, 1 LSan verify) | Not relevant |
| Development and churn experiments | Run on Ubuntu 24.04, output within the sections above | Not run |
Not lined: 32-bit builds, compilers newer than GCC 13.3 and Clang 18.1.3, macOS, different progress elements past the three measured, customized allocators, and timings on every other machine.

