3 ms·
It's been a long time since I've used C, but I recall strncpy being safe. I assume from context that I'm wrong, though.
by ringshall 6y ago
It's been a long time since I've used C, but I recall strncpy being safe. I assume from context that I'm wrong, though.
- WalterBright 6y agoEvery time I review code and see strncpy, I look closer because it's always used incorrectly. It's always about the terminating 0. Is the 0 there or not? Is the 0 part of n or not? Does the destination have to be n+1 in size for the 0? I quit using it myself because I could never remember just what the exact protocol was for 0.
- Gibbon1 6y agoYeah used naively strncpy leaves you an unterminated string. Also like all of them it's up to the caller to predetermine if they will fail if called. So instead of having the checks in one place inside the string function. You have them scattered all over the code if at all.
- WalterBright 6y agoThe irony of strncpy is it's supposed to eliminate memory corruption errors, but instead is a prolific source of them.
- Gibbon1 6y agoI think I read somewhere the provenience of strncpy was to copy strings into a fixed length field which is why it has the deranged behavior of not terminating the string. Think file systems where the max file name is 8 characters. Or compilers that truncated variable names at 31.
- johntb86 6y agoStrncpy doesn't add a \0 if it truncates the string, so the user has to remember to do that.
- Cloudef 6y agostrncpy is one of the trap functions. It's better avoided. Write your own or use snprintf.