cstringcopy

Practice to use memcpy or strncpy to copies the string into memory


I am writing a piece of simple practice to compare the usage of between memcpy or strncpy. I see that I can do this string copy using either of these two functions:

char * strncpy ( char * destination, const char * source, size_t num );

and

void * memcpy ( void * destination, const void * source, size_t num );

Simple practice

    char src[] = "Hello World";
    char dst[20];

    strncpy(dst, src, 5);
    printf("%zu-", strlen(dst));

    memcpy(dst, src, sizeof(dst));
    printf("%zu-", strlen(dst));

    strncpy(dst, src, 5);
    printf("%zu", strlen(dst));

The actually output

5-11-11

How can I understand what the behave differently with respect?

In general, how can I find out relative bytes of memory block different copied by using memcpy or strncpy?


Solution

  •     strncpy(dst, src, 5);
        printf("%zu-", strlen(dst));
    

    When the count is exhausted before a null character is found in the source, strncpy does not write a terminating null to the destination. Then dst may not be null-terminated, in which case the behavior of strlen is not defined. However, the fact “5” is printed is consistent with dst happening to contain a zero in dst[5].

        memcpy(dst, src, sizeof(dst));
        printf("%zu-", strlen(dst));
    

    Your src has only 12 bytes, while sizeof(dst) is 20, so this memcpy attempts to read bytes from beyond src. Again, the behavior is not defined. It likely copied into dst the 11 bytes of “Hello World”, the following null byte, and then eight bytes from whatever happened to be in memory after src.

        strncpy(dst, src, 5);
        printf("%zu", strlen(dst));
    

    At this point, dst likely contains the data described above, the 11 bytes of “Hello World” and the following null byte, and that causes strlen to return 11.