cstrcpystrncpy

how to use strncpy correctly?


I know strncpy is a safer version of strcpy as said here.

However, when I want to copy from src to dst and dst is not a clean buffer, I get unwanted results, which can be avoided by strcpy:

char *p = "123";
char a[10] = "aaaaaa";

strncpy(a,p,strlen(p));
printf("%s\n", a);   // 123aaa

strcpy(a,p);
printf("%s\n", a);   // 123 <- desired output, as the trailing a's are garbage

In my actual case, I know strlen(src) < sizeof(dst) (at least, if that isn't the case, the program will crash a lot sooner), so I can safely strcpy.

However, if strncpy is what I should use, then must I add after dst[strlen(src)] = '\0' to avoid garbage (or maybe better yet, init the buffer beforehand?)?


Solution

  • The third argument of strncpy is meant to represent the size of the target buffer. And when it fills it up, it doesn't add a null terminating character by design.

    If you have sufficient space for the terminator and you insist on strncpy, just pass strlen(p) + 1 so it will not assume it exhausted the target buffer.

    Like many already noted by now. This use of strncpy defeats the purpose, and is really no better than than a simple call to strcpy. The only practical use for strncpy, is if you want to overwrite a part of the string in-place (which is the use case you stumbled upon). Though that too is questionable use...