Hacker News new | past | comments | ask | show | jobs | submit login

Something like this is all you'll need: https://gist.github.com/jstimpfle/562b2c3e9fe537e378351bb9d5...

Explanation: A little macro that adds the correct element size. Of course, you can opt to add it by hand as well, or put it in the run-time data structures and only set it once at initilization time. I personally think these approaches are error-prone / ugly, though.

There is also the stretchy-buffer approach from Sean Barret, where you don't need to explicitly allocate bookkeeping data (capacity value in my example). That one puts the bookkeeping data and count in front of the actual data.

I prefer the explicit approach, though, and I MUCH prefer having an explicit count for growing vector-like things. Because I hate when I have parallel arrays and each one has its own count. Having a shared count variable for parallel arrays is much clearer.




BTW that code has a security vulnerability in it: the size computation can overflow and you can end up shrinking your buffer, and you will end up smashing your heap, and then bad things.


I know. I don't care. Partly because it's only an example and the requirements are not spec'ed out. Partly because you have potential overflows basically everywhere, if you disregard the context. Let's just say the caller is assumed to make sure there will be no overflow. (Or just add a no-overflow assertion - I don't care).




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: