memcpy vs strcpy including performance C++

(Last Updated On: February 25, 2019)

memcpy() function: memcpy function copies specified number of bytes from source buffer to destination buffer. Actually, programmer supply the size of data to be copied.

memcpy() does not check for any terminating null character in source buffer. Actually, it doesn’t care what content is there in the memory. Just it copy the specified number of bytes.

strcpy() function: This function copies the string from source into the destination buffer until it comes across the null termination character i.e. ‘\0’ in source string.

Prototype of strcpy(): char * strcpy ( char * destination, const char * source );


Example for strcpy() and memcpy() API in C Programing.

Below program has a source buffer that contains a string including ‘\0’ – terminating null character. i.e.

char source[16]=”interview\0sansar”;

We have placed a null character in this string to show that strcpy() function will copy string till it find ‘\0’ i.e. string “interview” into destination buffer.

And memcpy() will copy the entire byte, so, complete string including ‘\0’ null character resulting output as “interview\0sansar”

[Note that we have written display function (It traverse all memory slot of buffer, read charater and print to console) to see the difference in strcpy() and memcpy() output. As, printf() cannot show the difference as printf() funtion as soon as find null, it will stop printing.

For example, for below program if we use printf, it will print same result i.e. “interview” for both strcpy() and memcpy() functions.]



memcpy vs strcpy – Performance :

Memcpy() function will be faster if we have to copy same number of bytes and we know the size of data to be copied.
In case of strcpy, strcpy () function copies characters one by one until it find NULL or ‘\0’ character.

Note that if the string is very small, performance will not be noticeable. But, if we have large string, may be reading string from file of known size, at this point of time, we can consider performance. And If heavy string processing is going within a loop then yes we must consider choosing strcpy or memcpy function.