4 ms·
When I review C code, I look for strncpy, etc., and give them special attention. There's always a bug or two in it. 0-terminated strings not only have proven t
by WalterBright 6y ago
When I review C code, I look for strncpy, etc., and give them special attention. There's always a bug or two in it.
0-terminated strings not only have proven to be a rich source of bugs, they're remarkably inefficient as well [1]. Doing better was a major focus of the initial design of D.
[1] This is because of constantly scanning to get the length (which also necessitates reloading the string contents into the memory cache), and having to make copies of strings instead of just slicing them.
- aidenn0 6y agoWell you don't have to make copies of strings to slice them, just ask strtok! </s>
- abqexpert 6y agoIf you wanted to slice at an arbitrary point, then you would either have to lose some data in the original string, move or copy the original string to make space for the extra delimiter/null character, or have set up the string ahead of time to contain the delimiter in the desired position. If you are using strtok.
- souprock 6y agoThere is also the mangle-use-repair choice. I've done that with pathnames for creating nested directories. C programmers are expected to make the best choice based on the situation. The various choices trade off memory usage, CPU usage, source code readability, and program correctness.
- account42 6y ago> There is also the mangle-use-repair choice. Which is problematic for thread safety and depending on the source of the string (constant) may not be possible.
- souprock 6y agoIt's not problematic. C programmers are expected to avoid screwing that up. C is a full-power language. If available, strdupa() would be a fine way to get a suitable local copy of the string. Commonly though, the programmer knows that there will not be threads and can make the string non-constant.
- codezero 6y agoI encountered Hollerith constants in an ancient Fortran codebase I worked on and was thrilled to see folks were doing clever stuff with strings in the 60s. I wonder how much time was wasted in early computing (maybe not wasted really) because of the fear of incompatibility that is getting smaller and smaller as computing platforms coalesce into standardized-ish things. Watching the M1 roll out and how it doesn't seem to care much that x86 is a thing and gets along with its life has been fascinating.