Generic Containers in C: Vec

https://news.ycombinator.com/rss Hits: 9
Summary

Generic Containers in C: vec Martin Uecker, 2025-07-20 I discuss the implementation of type and bounds safe generic containers in C. Previously, I discussed a span type, and bounds checking using arrays. Here, I will discuss a vector type. A vector type is essentially a resizable array. A vector type could be used as in the following example. int main() { vec(int) *vec_ptr = calloc(1, sizeof *vec_ptr); if (!vec_ptr) // memory out abort(); for (int i = 0; i < 10; i++) vec_push(int, &vec_ptr, i); int sum = sum_vec(vec_ptr); free(vec_ptr); printf("sum: %d\n", sum); } In C, it is actually fairly easy to define a vector type. #define vec(T) struct vec_##T { ssize_t N; T data[/* .N */]; } It is very similar to the span type I discussed two weeks ago and you may want to read this post first. In comparison to the span type, the last element is not a pointer to an array but a so-called flexible array member, which extends the structure by an array of unknown length. Growing the Vector The key feature is that we can append elements to a vector, which we can implement using realloc. #define vec_push(T, v, x) \ ({ \ vec(T) **_vp = (v); \ ssize_t _N = (*_vp)->N + 1; \ ssize_t _S = _N * (ssize_t)sizeof((*_vp)->data[0]) \ + (ssize_t)sizeof(vec(T)); \ if (!(*_vp = realloc(*_vp, _S))) abort(); \ (*_vp)->N++; \ (*_vp)->data[_N - 1] = (x); \ }) Error Handling I simply terminate the program using abort in case memory can not be allocated. Of course, this may not be what you want. If you need to handle errors (e.g. in embedded or systems programming), you need to adapt the API to return an error. You might also notice that I use ssize_t instead of size_t. the idea is to use the signed overflow sanitizer to catch overflow. If overflow must be handled explicitly, C23's checked integers could be used. Why no Capacity Field? Many vector types include a capacity field, so that resizing on every push can be avoided. I do not include one, because simplicity is more important to me and realloc ...

First seen: 2025-07-26 05:11

Last seen: 2025-07-26 15:14