how to use strncpy correctly?
When code needs to copy a string to a destination and tolerates the result being not null character terminated nor fully copied, use the sizeof destination
for the size argument:
char a[10];
// strncpy(a,p,strlen(p));
strncpy(a, p, sizeof a);
// printf("%s\n", a);
printf("%.*s\n", (int) sizeof a, a);
When code wants to copy a string and detect insufficient memory problems via strncpy()
or needs null character '\0'
padding, also use the sizeof destination
.
char a[10];
strncpy(a, p, sizeof a);
if (a[sizeof a - 1] != '\0') {
// insufficient memory
// Maybe set last last character to the null character
a[sizeof a - 1] == '\0';
// or other more robust handling
return ERROR_INSUFFICIENT_MEMORY;
}
Otherwise do not use strncpy()
There are more efficient ways to detect insufficient memory than via strncpy()
when null character '\0'
padding is not needed. strncpy()
zero fills the rest, if any, of the un-copied buffer. The below consumes much time zero-filling just to provide a insufficiency check.
char a[1000];
strncpy(a, "abc", sizeof a);
if (a[sizeof a - 1] != '\0') {
....
Better alternatives employ strlen(), strlcpy(), memcpy()
. @Deduplicator.
See also strncpy or strlcpy in my case.
For a standard C lib one-liner, code could use snprintf()
and a line of error detection. A good compiler would be expected to analyse snprintf(a, sizeof a, "%s", p)
and emit efficient code.
// Copy with no overflow.
// 'a' is always null character terminated.
int len = snprintf(a, sizeof a, "%s", p);
if (len < 0 || (unsigned) len >= sizeof a) Report_truncated_copy();