c strncpy null terminated or not

beetlej picture beetlej · Dec 8, 2016 · Viewed 10.4k times · Source

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 of source to destination. If the end of the source C string (which is signaled by a null-character) is found before num characters have been copied, destination is padded with zeros until a total of num 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 and source shall not overlap (see memmove 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

Answer

SpacedMonkey picture SpacedMonkey · Dec 8, 2016

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.