strcpy vs. memcpy

strcpy terminates when the source string's null terminator is found. memcpy requires a size parameter be passed. In the case you presented the printf statement is halting after the null terminator is found for both character arrays, however you will find t[3] and t[4] have copied data in them as well.


strcpy stops when it encounters a NUL ('\0') character, memcpy does not. You do not see the effect here, as %s in printf also stops at NUL.


what could be done to see this effect

Compile and run this code:

void dump5(char *str);

int main()
{
    char s[5]={'s','a','\0','c','h'};

    char membuff[5]; 
    char strbuff[5];
    memset(membuff, 0, 5); // init both buffers to nulls
    memset(strbuff, 0, 5);

    strcpy(strbuff,s);
    memcpy(membuff,s,5);

    dump5(membuff); // show what happened
    dump5(strbuff);

    return 0;
}

void dump5(char *str)
{
    char *p = str;
    for (int n = 0; n < 5; ++n)
    {
        printf("%2.2x ", *p);
        ++p;
    }

    printf("\t");

    p = str;
    for (int n = 0; n < 5; ++n)
    {
        printf("%c", *p ? *p : ' ');
        ++p;
    }

    printf("\n", str);
}

It will produce this output:

73 61 00 63 68  sa ch
73 61 00 00 00  sa

You can see that the "ch" was copied by memcpy(), but not strcpy().

Tags:

C

Memcpy

Strcpy