Re:Generic dynamic array in 60 lines of C
by nice_byte on Tuesday February 28, 2023 @03:21PM
(#34974291)
I have been using this for years. Capacity is not size. A zero size array will have non zero capacity. All c code is unsafe.
[ Parent
| on HN ]
Re:Generic dynamic array in 60 lines of C
by klyrs on Tuesday February 28, 2023 @03:24PM
(#34974322)
Where do you check that capacity is nonzero? When capacity is zero, what happens on this line?
a.capacity <<= 1u;
"all c code is unsafe" is not an excuse to permit bloody obvious, undocumented memory overruns.I write a lot of c. Avoiding the unsafe bits, avoiding UB, is the skill required to write good c. "C code is unsafe" is a Rustacean marketing slogan. Don't believe it, but definitely don't practice it.
Re:Generic dynamic array in 60 lines of C
by nice_byte on Tuesday February 28, 2023 @03:36PM
(#34974467)
just don't initialize it with 0 capacity :-)
Re:Generic dynamic array in 60 lines of C
by skullt on Tuesday February 28, 2023 @04:06PM
(#34974844)
Why not just fix it? It's a trivial fix and has the added benefit that a zero-initialized DYN_ARR_OF(x) struct would be in a valid state, which is always nice. A struct with several dynamic arrays can then much simpler to initialize, for example.
For a library, if the user input is wrong, throw an error or an assertion failure. It shouldn't be causing an uninformative segmentation fault which your library does. The fix is a trivial. Why so defensive?