Hacker News new | ask | show | jobs
by orbital223 1202 days ago
DYN_ARR_RESET should probably be called DYN_ARR_INIT instead, as calling it more than once will leak memory.

The handling of endptr in DYN_ARR_RESIZE seems to be incorrect. If I have an array with 2 elements and capacity of 3 and I DYN_ARR_RESIZE it to 5, I now have an array with 5 elements, 3 of which are garbage values.

4 comments

~~Isn't the handling of `endptr` incorrect in `DYN_ARR_RESET` as well? `a.endptr = a.data;` feels very incorrect to me.~~

Nevermind, I see how it's supposed to work now.

To your point, `RESIZE` is definitely incorrect. It should be checking the length before calling `realloc`.

Thats just idiomatic C. Set the "pointer to end" to be equal to the "pointer to start".
The values are garbage because they haven't been initialized yet. Other code may write to those locations.
> The handling of endptr in DYN_ARR_RESIZE seems to be incorrect. If I have an array with 2 elements and capacity of 3 and I DYN_ARR_RESIZE it to 5, I now have an array with 5 elements, 3 of which are garbage values.

Why do you say this is wrong? That's exactly what I would expect.

> Why do you say this is wrong?

Exposing uninitialized memory as valid values tends to be a really bad idea.

that's the intended behavior.

this somewhat mirrors what happens with a std::vector when you call resize() except of course c doesn't have default ctors. the point of resize is to make exactly "size" elements of the dynamic array addressable.