Making a StringBuffer in C, and questioning my sanity
10 comments
·July 15, 2025o11c
remexre
How would you recommend doing that sort of "subtyping"? _Generic and macros?
o11c
Yup. It's a lot saner in C++, but people who refuse to use C++ for political reasons can do it the ugly way using C11 or GNU C.
amelius
I wonder how an LLM would rate this code.
ranger_danger
You might be interested in https://github.com/antirez/sds
fsckboy
neat, i like it, has some of the same ideas i've used in my string packages
but i did see a place to shave a byte in the sds data struct. The null terminator is a wasted field, that byte (or int) should be used to store the amount of free space left in the buffer (as a proxy for strlen). When there is no space left in the buffer, the free space value will be.... a very convenient 0 heheh
hey, OP said he wants to be a better C programmer!
ranger_danger
> The null terminator is a wasted field
I think that would break its "Compatible with normal C string functions" feature.
fsckboy
nooooo you don't understand. when the buffer is not full, the string will be zero terminated "in buffer" (which is how it works as is anyway). when the buffer is full, the "free count" at the end will do double duty, both as a zero count and a zero terminater
improgrammer007
I would rather focus on solving the main problem than reinvent the wheel. Just use C++ if perf is critical which gives you all these things for free. In this day and age the reasons for using C as your main language should be almost zero.
Hm, this implementation seems allergic to passing types by value, which eliminates half of the allocations. It also makes the mistake of being mutable-first, and provides some fundamentally-inefficient operations.
The main mistake that this makes in common with most string implementations make is to only provide a single type, rather than a series of mostly-compatible types that can be used generically in common contexts, but which differ in ways that sometimes matter. Ownership, lifetime, representation, etc.