3 ms·
(I'm the author of the linked blog post.) strcpy() can be used safely if you ensure that the destination array is big enough to contain the source string. (Yes
by _kst_ 11y ago
(I'm the author of the linked blog post.)
strcpy() can be used safely if you ensure that the destination array is big enough to contain the source string. (Yes, that can be non-trivial.)
strncpy() by itself doesn't write past the end of the destination array (assuming you call it correctly) -- but it can easily leave the destination without a terminating null character. This causes undefined behavior if you then pass the destination array to another string function. strncpy() is not dangerous by itself, but it can leave a booby-trap that causes other string functions to be dangerous.
This:
strncpy(dest, source, size);
can be replaced by this:
dest[0] = '\0';
strncat(dest, source, size);
which will leave the destination properly null-terminated.
Note that this can still quietly truncate the string. Ignoring that possibility is rarely the right thing to do.