I know there are a lot of answers on the web which say one is better than the other but I have come to this understanding of strncpy()
is better in terms of preventing unnecessary crashes in the system because of the missing '\0'
. As many people put it, it is quite defensive.
I have already gone through this link: Why should you use strncpy instead of strcpy?
Let's say:
char dest[5];
char src[7] = "Hello";
strncpy(dest, src, sizeof(dest)-1);
With this implementation (the key being sizeof(dest)-1
which always gives room for the '\0'
to be appended), even if the destination has a truncated string, isn't it always safer to use strncpy()
instead of strcpy()
? In other words, I'm trying to understand when would one want to use strcpy()
over strncpy()
?