tags:

views:

424

answers:

5

What is the difference between memcpy() and strcpy()? I tried to find it with the help of a program but both are giving the same output.

int main()
{
    char s[5]={'s','a','\0','c','h'};
    char p[5];
    char t[5];
    strcpy(p,s);
    memcpy(t,s,5);
    printf("sachin p is [%s], t is [%s]",p,t);
    return 0;
}

Output

sachin p is [sa], t is [sa]
+10  A: 

strcpy stops when it encounters a NULL, memcpy does not. You do not see the effect here, as %s in printf also stops at NULL.

Yann Ramin
then what could be done to see this effect
Sachin Chourasiya
@Sachin: Initialize `p` and `t` to something (all blanks, for example), then after copying, compare `p[3]` to `t[3]`. The `strcpy` didn't go beyond `p[2]`, where it found the null character, but the `memcpy` as directed copied five characters.
Jefromi
Minor nit-pick: strcpy stops when it encounters the NUL character (one "L"). NULL (two "L"s) is a compile-time constant for a pointer guaranteed not to point to any valid object.
Daniel Stutzbach
Thanks ,I got the answer
Sachin Chourasiya
+1  A: 

The main difference is that memcpy() always copies the exact number of bytes you specify; strcpy(), on the other hand, will copy until it reads a NUL (aka 0) byte, and then stop after that.

Jeremy Friesner
+1  A: 

Because of the null character in your s string, the printf won't show anything beyond that. The difference between p and t will be in characters 4 and 5. p won't have any (they'll be garbage) and t will have the 'c' and 'h'.

Thomas Jones-Low
+5  A: 

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.

fbrereto
+2  A: 

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 product 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().

egrunin
Thank you very much for the clear explanation.
Sachin Chourasiya