Search code examples
ccharmemcpyc-strings

memcpy not actual copying


    char buffer[2000];

    char boundary[]= "--this-is-a-boundary\n";
    char header1_a[]= "Content-Disposition: form-data; name=\"metadata\"\n";
    char header1_b[]= "Content-Type: application/json; charset=UTF-8\n\n";
    printf("%s%s%s\n\n\n\n", boundary, header1_a, header1_b);
    std::memcpy(buffer, boundary, sizeof boundary);
    std::memcpy(buffer + sizeof boundary, header1_a, sizeof header1_a);
    std::memcpy(buffer + sizeof boundary + sizeof header1_a, header1_b, sizeof header1_b);
    std::memcpy(buffer + sizeof boundary + sizeof header1_a + sizeof header1_b,
                strJSONout, sizeof strJSONout);
    printf("%s", buffer);

But the output is :

--this-is-a-boundary

What happen to the rest of the string? I expect buffer contains all of the these character arrays...

Is it because of the fact that I have copied NULL-terminated char array?


Solution

  • When you copy the first string, you get something like

    --this-is-a-boundary\n\0

    Then you copy the next string. You get

    --this-is-a-boundary\n\0Content-Disposition: form-data; name=\"metadata\"\n\0

    Since strings are \0-terminated, the string is still the part up to the first \0.

    I think, it is quite clear, what you have to do …:

    std::memcpy(buffer + sizeof boundary - 1, header1_a, sizeof header1_a);
    

    This overwrites the \0, when you append the next string.