3 ms·
There is a very simple, efficient solution: always put a null termination character in the end position of the destination after the strncpy(). If the source is
by gvb 11y ago
There is a very simple, efficient solution: always put a null termination character in the end position of the destination after the strncpy(). If the source is longer than the destination, it will properly terminate the destination. If it isn't longer, it didn't cost (hardly) anything.
Unfortunately, it isn't automatic so some times humans will forget to do it.
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
char *src = "Gobblygook is a long string";
char dest[5];
strncpy(dest, src, sizeof(dest));
dest[sizeof(dest) - 1] = '\0';
printf("src = %s\ndest = %s\n", src, dest);
}
make test
./test
src = Gobblygook is a long string
dest = Gobb
- pjc50 11y agoWhile I've done this myself, it's not a 100% solution, because now you get a truncated string that further processing may not be expecting. For example, if you validate the un-truncated string somehow then take a copy of it, the copy may be invalid.