cbufferc-stringsstrncpy

Problem on strncpy with source string longer than destination array


I tried to think how to make the function strncpy and I met this problem.

    char src[] = "123456789A";
    char dest[10];
    int n = 10;
    printf("strncpy:%s\n", strncpy(dest, src, n));

Output

strncpy:123456789A123456789A

What is happening ?


Solution

  • The quick answer: strncpy is not your friend!

    strncpy is not a safer version of strcpy, it will copy up to n characters from src and if src is shorter, will pad the destination with null bytes up a total of n characters.

    If the source string has n or more characters, the destination array will not be null terminated and passing to printf("%s", will have undefined behavior: printf will keep reading and printing bytes from memory after the end of dest, until it finds a null byte or until this undefined behavior causes other unpredictable side effects...

    The semantics of strncpy are counter-intuitive and error-prone, avoid usng this function. See this article for a long answer: https://randomascii.wordpress.com/2013/04/03/stop-using-strncpy-already/