Comment by ufo

1 day ago

A big footgun with strncpy is that the output string may not be null terminated.

Yeah but fixed width strings don’t need null termination. You know exactly how long the string is. No need to find that null byte.

  • Until you pass them as a `char *` by accident and it eventually makes its way to some code that does expect null termination.

    There’s languages where you can be quite confident your string will never need null termination… but C is not one of them.

    • You don’t do that by accident. Fixed-width strings are thoroughly outdated and unusual. Your mental model of them is very different from regular C strings.

      4 replies →

  • Good luck though remembering not to pass one to any function that does expect to find a null terminator.

    • Ignore the prefix and always treat strncpy() as a special binary data operation for an era where shaving bytes on storage was important. It's for copying into a struct with array fields or direct to an encoded block of memory. In that context you will never be dependent on the presence of NUL. The only safe usage with strings is to check for NUL on every use or wrap it. At that point you may as well switch to a new function with better semantics.

      2 replies →

    • That's not a problem with strncpy, right? Fixed width records are a thing of the past, and even then it was only used for on-disk storage.