4 ms·
>It still boggles the mind how a function that leaves a C string potentially unterminated ever even made it into the standard... Easy to say with 50 years of h
by krelian 4y ago
>It still boggles the mind how a function that leaves a C string potentially unterminated ever even made it into the standard...
Easy to say with 50 years of hindsight. These are the pioneers we are talking about here. It boggles the mind how much they got right.
- kstenerud 4y agoWhile strcpy is forgivable considering it came from the primordial soup, there is no excuse for strncpy since it was designed to solve the problems with strcpy. And the string library is full of gaffes like this.
- tialaramex 4y agoNo, strncpy is not "designed to solve the problems". strncpy is a function to fill out fixed size data structures such as some on-disk data structures, with a variable length string it right pads the structure with null bytes. It does exactly what it was supposed to do, something that was pretty useful in 1970s UNIX programming but rarely if ever what you need today.
- icedchai 4y agoEvery teen hacker I knew had their own "my_strncpy" function that did something like strncpy(dst, src, len); dst[len-1] = 0;
- nicoburns 4y ago> Easy to say with 50 years of hindsight. These are the pioneers we are talking about here. Eh, well kinda. Languages with decent string handling predate C, so it's not like there wasn't precedent to follow. The creators of C were pioneers, but they were also people who favoured a quick, hacky approach over a clean careful one. That has certain advantages, but it's rather unfortunate that C has become so foundational and we've been stuck with those hacks.
- flohofwoe 4y agoWhat would those languages be? I'm only used to relatively modern languages with "decent string handling", but they almost always treat strings as opaque high level objects with dynamic memory allocation under the hood. Such an approach wouldn't exactly fit into the C philosophy. Also, once UNICODE is added to the mix (which involves a lot more than just the text encoding), a decent string processing library isn't exactly trivial, it either needs a very big chunk in the stdlib, or a a handful of specialized 3rd party libs). Even in Zig, which has a very decent modern low-level approach for handling string data, people used to high level string objects would probably be shocked at how 'inconvenient' it is to work with string data (which can be solved with specialized libraries though).
- nicoburns 4y agoPascal would be one example. > with dynamic memory allocation under the hood C strings are typically dynamically allocated, are they not?
- icedchai 4y agoNot in the way that is described here. I took "always treat strings as opaque high level objects with dynamic memory allocation under the hood" to mean that the string would have operations, like append, that would reallocated/resize the string if needed. C strings are definitely not that.