5 ms·
How do you intend to fix the strings library? beyond strlen() and _maybe_ the search functions like strchr() there really isn't much you should use. And those f
by jstimpfle 4y ago
How do you intend to fix the strings library? beyond strlen() and _maybe_ the search functions like strchr() there really isn't much you should use. And those functions are _fine_.
Some of the string functions, like strtok() or strcat(), and I would also include strdup(), are broken beyond repair and should simply not be used. The only way to "fix" the library would be to remove these functions, but I assume this would create more trouble with legacy code than it's worth.
C strings are mostly a useful storage format for small strings, including string literals, and as a "default" string type for the little basic functionality that is expected to be part of C to support a small program growing up - including printf() and friends.
For longer strings, you are expected to build datatypes that fit your usecase, and that includes decisions about memory management. It should not be the responsibility of the language to make these decisions for you.
- pjmlp 4y agoBy having something like SDS[0] as part of the standard library, but that is clearly asking too much. [0] - https://github.com/antirez/sds https://github.com/antirez/sds
- fullstop 4y agoI get strtok and strcat, but what's wrong with strdup?
- jstimpfle 4y agoIt's only very marginally useful, strdup(x) is equivalent to malloc(strlen(x)). It is one of the few functions that allocate, but it doesn't have "alloc" in its name, putting more of an onus on the programmer to free() appropriately. Also, it's advocating bad programming style. Just mallocing random small things all over the place is not how you structure programs well. (Instead, most strings should be in a pool or in another context that is more local than the malloc() heap, so individual strings can be released at once without having to track all the strings attached to a million different structures).
- fullstop 4y agoOther POSIX functions, such as glob, also allocate memory and don't have alloc in the name. It's something that I use. Maybe not frequently, but I definitely use it. Also, it is in no way equivalent to malloc(strlen(x)). You're off by one byte and you've not copied any of the string.
- jstimpfle 4y agoOops, see how my mind became lazy when thinking about such a boring, tasteless function? A function like memdup() would be slightly more useful. At least, glob() has its own globfree() function, leaving room for slightly more mindful organization.