This means that, for example, if your source string contains 20 characters plus a zero delimiter, and your strncpy indicates less than 21 characters, the target string will not have a zero to it.
This is because of how it works: strncpy ensures that it will write exactly N bytes, where N is the length value passed to.
If the length of the source string (without the zero byte) is less than this, it will fill the destination area with zeros. If it is equal to or greater, you will not get the zero added to the destination.
This means that technically it cannot be the C string you get. This can be solved using code, for example:
char d[11]; // Have enough room for string and null. strncpy (d, s, 10); // Copy up to 10 bytes of string, null the rest. d[10] = '\0'; // Then append null manually in case s was too long.
You select 11 bytes (array indexes 0.10), copy up to 10 (indexes 0..9), then set the 11th (index 10) to zero.
Here is a diagram showing three ways to write strings of different sizes to a 10-digit area using strncpy (d, s, 10) , where . represents a null byte:
sd ------------- ---------- Hello. Hello..... Hello Fred. Hello Fred Hello George. Hello Geor
Note that in the second and third cases it is not written anywhere so that if you treat d as a string, you will probably be disappointed with the result.
source share