C has no built-in vector type, so "vectors in C" means a dynamic array you build yourself: a pointer to heap memory, a length, a capacity, and realloc to grow it when it fills up. The working version is about thirty lines, and the one detail most examples get wrong is what to do when realloc fails.
If you came here from C++, std::vector does this bookkeeping for you. C leaves it to you, which is why the code below tracks three things per array. For the other meanings of the word, including the physics one, see what a vector is in computing.
The minimal dynamic array in C
This is a growable array of int. It needs stdlib.h for the allocation functions, stddef.h and stdint.h for size_t and SIZE_MAX, and stdbool.h for bool. I have not compiled it on this machine, so treat the output below as example output.
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int *items;
size_t length;
size_t capacity;
} IntVector;
void vec_init(IntVector *vec) {
vec->items = NULL;
vec->length = 0;
vec->capacity = 0;
}
bool vec_push(IntVector *vec, int value) {
if (vec->length == vec->capacity) {
if (vec->capacity > SIZE_MAX / 2) {
return false;
}
size_t new_capacity = vec->capacity == 0 ? 4 : vec->capacity * 2;
if (new_capacity > SIZE_MAX / sizeof *vec->items) {
return false;
}
int *grown = realloc(vec->items, new_capacity * sizeof *grown);
if (grown == NULL) {
return false;
}
vec->items = grown;
vec->capacity = new_capacity;
}
vec->items[vec->length++] = value;
return true;
}
void vec_free(IntVector *vec) {
free(vec->items);
vec_init(vec);
}
int main(void) {
IntVector squares;
vec_init(&squares);
for (int n = 0; n < 10; n++) {
if (!vec_push(&squares, n * n)) {
fprintf(stderr, "out of memory\n");
vec_free(&squares);
return EXIT_FAILURE;
}
}
for (size_t i = 0; i < squares.length; i++) {
printf("%d ", squares.items[i]);
}
printf("\nlength=%zu capacity=%zu\n", squares.length, squares.capacity);
vec_free(&squares);
return EXIT_SUCCESS;
}
Example output:
0 1 4 9 16 25 36 49 64 81
length=10 capacity=16
The capacity goes 4, 8, 16 as the length passes 4 and 8. Ten elements fit in 16 slots, so six slots are allocated but unused. That spare room is the whole point: most pushes only write one element and do not touch the allocator.
How the growth works
The array tracks two numbers. length is how many elements are stored. capacity is how many fit in the memory currently allocated. A push when length == capacity asks realloc for a bigger block.
Two facts from the C reference make this work. First, if the pointer passed to realloc is NULL, the call behaves like malloc(new_size). That is why vec_init can leave items as NULL and the first push needs no special case. Second, the contents are preserved up to the lesser of the old and new sizes, whether the block is extended in place or moved. The new part of the block is uninitialized, so never read a slot you have not written.
What to do when realloc fails
This is the bug in many tutorial vectors:
vec->items = realloc(vec->items, new_capacity * sizeof *vec->items); /* wrong */
The cppreference page for realloc says that if there is not enough memory, the old block is not freed and a null pointer is returned. In the line above, the null result overwrites vec->items, and the only pointer to the still-allocated block is gone. The program leaks the memory and then crashes on the next access through the NULL pointer.
The version in the listing assigns the result to a temporary, grown, and checks it. Only after the check passes does it replace vec->items. On failure the vector is left unchanged and still usable, and the caller decides what to do: report an error, free everything and exit, or keep working with the elements it already has.
Why the pointer changes
On success, the reference states that the original pointer is invalidated and any access to it is undefined behavior, even if the reallocation happened in place. Only the returned pointer may be used. This has a practical consequence for vectors:
int *first = &squares.items[0];
vec_push(&squares, 100);
printf("%d\n", *first); /* undefined behavior if the push reallocated */
Never keep a pointer to an element across a push. Keep the index instead and look the element up each time with squares.items[index]. C++ std::vector has the same rule for iterators and references, so the habit carries over.
Why capacity doubles
A realloc may copy the whole array. If the capacity grew by one on every push, filling an array of n elements would cost a copy on almost every push. Multiplying the capacity by a constant factor makes reallocations rarer as the array grows: after the capacity reaches 1,024 the next growth only happens at the 1,025th element. The cost of a push, averaged over many pushes, stays roughly constant. The factor 2 is a common choice, not a requirement. The starting capacity of 4 is also arbitrary.
The two overflow checks in vec_push guard the size arithmetic. realloc takes a byte count, and new_capacity * sizeof *grown can wrap around on a huge array. A wrapped value would allocate a block far smaller than the code believes it has, and the next write would land outside it. The checks refuse to grow instead.
Freeing the memory correctly
Every block from malloc or realloc must be released with free. The reference lists these as undefined behavior:
- Freeing a pointer twice, or freeing it after
reallochas already succeeded with it as the argument. - Freeing a value that was not returned by an allocation function.
- Reading or writing through the pointer after it was freed.
Passing a null pointer to free is safe and does nothing. That is why vec_free works on an empty vector that never allocated, and why it resets the struct afterward: a second call to vec_free then frees NULL instead of the old block.
Other operations you will want
Reading and writing by index needs no function, but bounds checking does. In C, items[i] with i >= length is not caught for you. A small getter that checks the index, or an assert(i < vec->length) in debug builds, catches mistakes early. Removing the last element is just vec->length-- after checking that the length is above zero; the memory stays allocated for later pushes. Removing from the middle means shifting the later elements down with memmove from string.h, which is safe for overlapping ranges.
To store another type, change the type of items, or write the struct once for void * with an element size field. The typed version is simpler and lets the compiler check your calls, so start there.
Check it with a memory tool
Allocation bugs often run without visible symptoms. Build your test program with AddressSanitizer (-fsanitize=address in GCC and Clang) or run it under Valgrind on Linux. Either one reports leaks, double frees and use-after-free errors that otherwise pass silently. Run the listing above through one of them before copying the pattern into a larger project.
If it crashes or leaks
- Crash on the first push: the struct was not initialized. Call
vec_init, or zero the struct, before the first push. A garbagecapacitymakes the code skip the allocation. - Crash after many pushes: look for a saved element pointer that outlived a reallocation, as in the example above.
- Leak report at exit: a path returns without calling
vec_free, often an early error return. - Wrong values at the end: a slot was read before being written. New memory from
reallocis uninitialized.
Frequently asked questions
- Does C have a vector like C++ std::vector?
- No. The C standard library has no growable array type. You build one yourself from a pointer, a length, a capacity and the allocation functions malloc, realloc and free. The pattern is small enough to write in about thirty lines.
- Why not assign the result of realloc straight back to the same pointer?
- If realloc fails it returns a null pointer and leaves the original block allocated and valid. Writing p = realloc(p, n) would overwrite your only pointer to that block with NULL, so you could no longer free it, which is a memory leak. Assign to a temporary first and check it.
- Why double the capacity instead of growing by one?
- Each realloc may have to copy the whole array. Growing by one element on every push would copy on every push. Multiplying the capacity by a constant factor, such as 2, means reallocations become rarer as the array grows, so the average cost of a push stays low.
- Is a pointer into the array still valid after a push?
- Not necessarily. After a successful realloc, the old pointer is invalid, even if the block was resized in place. Any pointer you saved to an element before the push must be recomputed from the new items pointer and the index. Store indexes instead of element pointers.