4 ms·
I'm not sure how "If you thought strncpy always returns a string, you were wrong" is an argument in favor of its safety. It is always possible to write correct
by geofft 10y ago
I'm not sure how "If you thought strncpy always returns a string, you were wrong" is an argument in favor of its safety. It is always possible to write correct code in C if you use every API correctly, but that doesn't mean every API is safe. "Safety" is a term that refers to the robustness of a particular language or API when humans, who occasionally make mistakes, and who have some particular mental model of what they want to do that doesn't line up perfectly with the language spec, write code.
And yes, I would absolutely argue that malloc is unsafe. Certainly it's "less safe" in the language of this thread than calloc, and certainly it's completely type-unsafe. But more than that, if you want a string, there should be a function that allocates and returns an empty but well-formed string in one action, and malloc should be the lower-level unsafe API that this function uses. The myriad alternatives to C strings that I mentioned in my comment all support this - bstring has bfromcstr(""), GLib has g_string_new(""), Rust has String::new(), Ruby has "", and so forth.
- taeric 10y agoAt argument here is only if it safer. Not if it is safe. Think of it as the argument that sharper knives are safer than duller ones. Certainly not true for untrained users. But widely true for trained ones.