Search code examples
carraysprintfc-stringsmemcpy

Copying array into array into another array (of strings), duplicate its content in C


I'm starting learning fundamentals of C, and I got stuck with this simple program which produce this strange output. What I'm trying to do is to copy the content of an array into another array with the memcpy() function.

#include <stdio.h>
#include <string.h>

int main()
{   
    char source[13] = "Hello, World!";
    char destination[13];

    memcpy(&destination, &source, 13);

    printf("%s\n", destination);
    return 0;
}

The "strange" output is:

Hello, World!Hello, World!(

What makes me wondering why it's happening, is that if I change, in memcpy, from 13 to 12 the output is right, obviously without the last char:

Hello, World

So, my question is: "What I am missing? Is there some theoretical fundamental I don't know?"


Solution

  • Every string in C needs terminating zero. So the length of your array in too small to accommodate the string and the program invokes the UB.

    Change to:

    #include <stdio.h>
    #include <string.h>
    
    int main()
    {   
        char source[14] = "Hello, World!";
        char destination[14];
    
        memcpy(&destination, &source, 14);
    
        printf("%s\n", destination);
        return 0;
    }
    

    https://godbolt.org/z/Z_yyJX