Stop using strncpy()

Don't use strncpy(). Ever. I mean it. I have seen advice that suggests using strncpy() as a “safe” alternative to strcpy(). It's not. This is from the man page:

char *strncpy(char *dest, const char *src, size_t n);

The basic issues with strncpy() are:

What you should be using is std::string.

Not every use is a bug. But since you need to check the length of the source string anyhow I can't see how it's of any real value.

I had been under the impression that the use for which it was indented originally was writing the d_name member of the direct struct. But now that I have poked around some old Unix source trees I don't see that usage at all.

No lie, I see this pattern all the time:

strncpy(tst, s, strlen(s) + 1);

Did lint at one time emit a warning if you used plain old strcpy()?

This is some real code that shows another typical pattern:

/* local_dev_name should be null terminated. */
void ares_set_local_dev(ares_channel channel,
                        const char* local_dev_name)
{
  strncpy(channel->local_dev_name, local_dev_name,
          sizeof(channel->local_dev_name));
  channel->local_dev_name[sizeof(channel->local_dev_name) - 1] = 0;
}

The above silently truncates the string. I think you can argue that this is a bad thing.

Now imagine that the string is UTF-8 encoded: this could fracture a codepoint.

After I wrote this post, I was pointed to this thread about this post. And looking around I found this one, too.

Valid HTML 5