97

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]
chqrlie
  • 131,814
  • 10
  • 121
  • 189
Sachin
  • 20,805
  • 32
  • 86
  • 99

9 Answers9

140

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

egrunin
  • 24,650
  • 8
  • 50
  • 93
  • 3
    Hello, I know that post is old, but I have two questions regarding it. First - `printf("%2.2x ", *p);` - why did You limit printf to 2.2 ? Besides I can see NO dot at all... Second - `printf("%c", *p ? *p : ' ');` - what does this test really check? If `*p` ? Thanks in advance for Your answer! – Peter Cerba Aug 30 '12 at 09:02
  • 16
    In a printf statement, "x" means "base 16". "2.2" means: two and only two digits. The `*p` test means: "if you hit a null, print a space." – egrunin Aug 30 '12 at 15:43
113

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.

alxgb
  • 543
  • 8
  • 18
Yann Ramin
  • 32,895
  • 3
  • 59
  • 82
  • 2
    @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. – Cascabel May 24 '10 at 16:23
  • 11
    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 May 25 '10 at 01:52
  • 1
    if dest and src overlap, strcpy will throw out a seg-fault? – Alcott Sep 16 '11 at 12:37
13

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
  • 35,429
  • 19
  • 126
  • 178
10

strcpy copies character from source to destination one by one until it find NULL or '\0' character in the source.

while((*dst++) = (*src++));

where as memcpy copies data (not character) from source to destination of given size n, irrespective of data in source.

memcpy should be used if you know well that source contain other than character. for encrypted data or binary data, memcpy is ideal way to go.

strcpy is deprecated, so use strncpy.

Brian
  • 14,610
  • 7
  • 35
  • 43
Viswesn
  • 4,674
  • 2
  • 28
  • 45
  • I don't know where did you see [`strcpy()`](https://man7.org/linux/man-pages/man3/strcpy.3.html) being deprecated. – Rohan Bari Jan 30 '21 at 20:50
  • 2
    @RohanBari It's a royal outrage if this is someone with only MSVC experience speaking about "_deprecated functions_" all over again for the billionth time – An Ant Feb 25 '21 at 17:12
  • `strcpy()` is **not** _deprecated_, it's only _discouraged_ (because `strncpy()` is less vulnerable to buffer overruns). Not the same thing at all. – egrunin Dec 29 '22 at 16:50
4

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
  • 70,199
  • 15
  • 131
  • 234
3

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'.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
Thomas Jones-Low
  • 7,001
  • 2
  • 32
  • 36
3
  • Behavior difference: strcpy stops when it encounters a NULL or '\0'
  • Performance difference: memcpy is usually more efficient than strcpy, which always scan the data it copies
euccas
  • 755
  • 9
  • 13
  • Performance-wise, it should really depend on the compiler and the platform. I've tested on two different environments and got these results: On Linux ARMv7L, `memcpy` was 1.5x faster than `strcpy`. However, on Linux x86_64, using GCC 13.1.1 and Clang 16.0.5, `strncpy` and `strcpy` both was faster than `memcpy` by 10% (maybe because of a modern compiler implementation?). Your mileage may vary, so you should test it yourself. – MAChitgarha Jul 26 '23 at 10:40
2

The problem with your test-program is, that the printf() stops inserting the argument into %s, when it encounters a null-termination \0. So in your output you probably have not noticed, that memcpy() copied the characters c and h as well.

I have seen in GNU glibc-2.24, that (for x86) strcpy() just calls memcpy(dest, src, strlen(src) + 1).

Jaspar L.
  • 31
  • 7
1

printf("%s",...) stops printing the data when null is encountered, so both the outputs are same.

The following code differentiates between strcpy and memcpy:

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

int main()
{
    char s[5]={'s','a','\0','c','h'};
    char p[5];
    char t[5];
    int i;
    strcpy(p,s);
    memcpy(t,s,5);
    for(i=0;i<5;i++)
        printf("%c",p[i]);
        printf("\n");
    for(i=0;i<5;i++)
        printf("%c",t[i]);

    return 0;
}
Ardent Coder
  • 3,777
  • 9
  • 27
  • 53