strncpy() supposedly protects from buffer overflows. But if it prevents an overflow without null terminating, in all likelihood a subsequent string operation is going to overflow. So to protect against this I find myself doing:
strncpy( dest, src, LEN ); dest[LEN - 1] = '\0'; man strncpy gives:
The
strncpy()function is similar, except that not more thannbytes ofsrcare copied. Thus, if there is no null byte among the firstnbytes ofsrc, the result will not be null-terminated.
Without null terminating something seemingly innocent like:
printf( "FOO: %s\n", dest ); ...could crash.
Are there better, safer alternatives to strncpy()?
extern char *strncpy(char * restrict s1, const char * restrict s2, size_t n);'): The strncpy() function copies at most n characters from s2 into s1. If s2 is less than n characters long, the remainder of s1 is filled with `\0' characters. Otherwise, s1 is not terminated.