The problem is that you're using strncpy
, rather than strcpy
. And
the way you're using it, it doesn't copy the terminating \0
.
In practice, because strncpy
may leave a string without a \0
terminator, it's best to avoid it. In your case, strcpy
alone is fine, since you've just allocated a sufficiently large buffer. In the more general case, you may have to use strlen
, to ensure that the string you have fits in the target buffer (without ever forgetting to add 1 to the results, for the \0
).
If the situation occurs a lot, you might want to write your own version
of strncpy
, which works (i.e. guarantees a terminating \0
, and
doesn't copy or write more characters than necessary). Something like:
void
stringCopy( char* dest, int maxLength, char const* source )
{
assert( maxLength > 0 );
char* end = dest + maxLength - 1;
while ( dest != end && *source != '\0' ) {
*dest = *source;
++ dest;
++ source;
}
*dest = '\0';
}
(This function actually exists, under the name strcpy_s
in C 2011, but
it isn't widely implemented; Microsoft has it, but I've not seen it
elsewhere.)