strcpy vs memcpy

strcpy() and memcpy() lives in same header file (string.h in C and cstring in C++) and has similar purpose in their lives – “to create copies”. But they are different in the way they work.

strcpy():

syntax: char *strcpy(char *dest, char *src);

  • copies the string at src, including its terminating '\0', to the memory at dest
  • will only work on “strings”.
  • returns dest.

memcpy():

syntax: void *memcpy(void *dest, const void *src, size_t n);

  • copies n bytes of memory from src to dest memory area.
  • will work on a “portion of memory”, so it can be used to copy any data type that C/C++ supports.
  • returns dest.

That’s not all the story, the major difference is explained by the below figure and program:

Example:

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
    char src[10] = {'H','I', '\0', 'H', 'E', 'L', 'L', 'O'};
    char dst[10];
    strcpy(dst, src);
    for (int i = 0; i < 10; i++)
    {
        printf("strcpy - Destination String Position [%d] : [%c]\n", i, dst[i]);
    }
    
        printf("\n");
    memcpy(dst, src, 10);
    for (int i = 0; i < 10; i++)
    {
        printf("memcpy - Destination String Position [%d] : [%c]\n", i, dst[i]);
    }
    
        printf("\n");
}

When source string is copied using memcpy(), it copies upto 10 – bytes in this example (3rd argument indicates the no. of bytes to copy) even it encounter '\0' in middle of copying.

Output:

strcpy - Destination String Position [0] : [H]
strcpy - Destination String Position [1] : [I]
strcpy - Destination String Position [2] : []
strcpy - Destination String Position [3] : []
strcpy - Destination String Position [4] : []
strcpy - Destination String Position [5] : []
strcpy - Destination String Position [6] : []
strcpy - Destination String Position [7] : []
strcpy - Destination String Position [8] : []
strcpy - Destination String Position [9] : []
memcpy - Destination String Position [0] : [H]
memcpy - Destination String Position [1] : [I]
memcpy - Destination String Position [2] : []
memcpy - Destination String Position [3] : [H]
memcpy - Destination String Position [4] : [E]
memcpy - Destination String Position [5] : [L]
memcpy - Destination String Position [6] : [L]
memcpy - Destination String Position [7] : [O]
memcpy - Destination String Position [8] : []
memcpy - Destination String Position [9] : []