r/C_Programming • • May 26 '26

Project Small and fast vector implementation

https://github.com/ephf/vector

Hello, just wanted to share this small (<150 lines) header for dynamic arrays in C. Feel free to look through it and show what could be done better or ask questions. AI was not involved in the making of this.

9 Upvotes

15 comments sorted by

View all comments

Show parent comment

1

u/SeaInformation8764 May 30 '26

That's something that hand't really crossed my mind. I know you can get alignment info using specific operators so I'll try to look into that.

1

u/ischickenafruit May 30 '26

IMHO using the user supplied data type to allocate the memory and size, then over allocating and doing the maths at alloc time to figure out your context size and alignment is a better approach. This would fix the UB problem.

That said, you’ve got a bigger performance problem which is you really want the context structure and only the tail of the vector in cache. What you’re doing now potentially pollutes a lot more of your cache. Having a void* in your structure solves both and an accessor macro would make it just as convenient.

It’s also worth considering of a flat array is really worth the trouble you’re going to. Reallocs are expensive and they’re either rare (ie a vector is not the right approach) or common, ie a vector is not the right approach. A power of 2 slab allocator with macros to access. Just a thought.