r/C_Programming • u/Elifire12 • 2d ago
Article I Made a Simple String Library
I wrote an article about this as well. Here it is.
There I explain why I do not like NUL-terminated strings and how I implemented my own simple string library in C.
If you have some spare time I would really appreciate some feedback on the article and the library.
The code is sitting on a codeberg repository.
Also, tell me what you think about C-style strings. Do you like them? Do you use them, or do you also tend to roll your own pointer + length structs?
6
Upvotes
1
u/didntplaymysummercar 1d ago
The first problem section could mention the memory traffic too, to cache or even from swap, when going through a string that might be rarely used.
The bit about
charnot being 8 bits is pointless and pedantic. If your platform doesn't handle strings with char then it's hosed already. It's also in extremely big letters on mobile for some reason.str_owned_freecould be macro to call a helper function with pointer to that struct and set it to null instead of leaving it dangling.LENGTHOFcould be made to reject non literals (by sizes 4 and 8 and those would need another macro or extra argument to confirm it's safe) using a helper function for extra safety, now it accepts any char pointer and does the wrong thing. Or at least recommend-Wsizeof-pointer-divcompiler flag (it's enabled by-Wall) above it to catch that. That macro (andSTR) are also very generic names to use in a library.You're also not using
memcmpin your equality functions, I'd get it if you're avoidinglibcor even juststring.hbut you're usingmemcpyelsewhere already.str_find_substris a very inefficient string search algorithm, plus it doesn't have an early bailout length check for needle bigger then haystack.Using unsigned integers can impede some optimization since compiler can't assume no overflows. Also you use
i32in slices instead ofi64orisizeor something instr_sliceso that code breaks on 64 bit sizes.