At the following regarding strncpy: http://www.cplusplus.com/reference/clibrary/cstring/strncpy/, it mentions the following:
No null-character is implicitly appended to the end of destination, so destination will only be null-terminated if the length of the C string in source is less than num.
What is meant by this sentence?
It means that, for example, if your source string is 20 characters plus a null terminator and your
strncpyspecifies less than 21 characters, the target string will not have a null appended to it.It’s because of the way it works:
strncpyguarantees that it will write exactly N bytes where N is the length value passed in.If the length of the source string (sans null byte) is less than that, it will pad the destination area with nulls. If it’s equal or greater, you won’t get a null added to the destination.
That means it may not technically be a C string that you get. This can be solved with code like:
You allocate 11 bytes (array indexes 0..10), copy up to 10 (indexes 0..9) then set the 11th (index 10) to null.
Here’s a diagram showing the three possibilities for writing various-sized strings to a 10-character area with
strncpy (d, s, 10)where.represents a null byte:Note that in the second and third case, no null byte is written so, if you treat
das a string, you’re likely to be disappointed in the outcome.