I am reading this document, it says:
char *strncpy(char *destination, const char *source, size_t num);
Copy characters from string Copies the first
num
characters ofsource
todestination
. If the end of thesource
C string (which is signaled by a null-character) is found beforenum
characters have been copied,destination
is padded with zeros until a total ofnum
characters have been written to it.No null-character is implicitly appended at the end of destination if source is longer than
num
. Thus, in this case,destination
shall not be considered a null terminated C string (reading it as such would overflow).
destination
andsource
shall not overlap (seememmove
for a safer alternative when overlapping).
But I am confused by this statement:
in this case, destination shall not be considered a null terminated C string (reading it as such would overflow)
Since if num > strlen(source)
, it will pad with '\0'
at the end, '\0'
is actually a null (terminating) character in a string, why it shall not be considered a null-terminated C string?
I have written below code to verify:
char from[] = { 'h', 'e', 'l', 'l', 'o', '\0' };
char to[1024];
for (int i = 0; i < 1024; i++) {
to[i] = 'e';
}
strncpy(to, from, 1024);
printf("from %s\n", from);
It works fine with below output:
from hello
to hello
It's talking about the case when strlen(source)
> num
. It will only copy num
chars, none of which is a NUL and it will not add a NUL.