Search code examples
cstrncpy

strncpy introduces funny character


When I run some code on my machine then it behaves as I expect it to.

When I run it on a colleagues it misbehaves. This is what happens.

I have a string with a value of:

croc_data_0001.idx

when I do a strncpy on the string providing 18 as the length my copied string has a value of:

croc_data_0001.idx♂

If I do the following

myCopiedString[18]='\0';
puts (myCopiedString);

Then the value of the copied string is:

croc_data_0001.idx

What could be causing this problem and why does it get resolved by setting the last char to \0?


Solution

  • According to http://www.cplusplus.com/reference/clibrary/cstring/strncpy/

    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 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.

    Thus, you need to manually terminate your destination with '\0'.