memcpy vs strcpy including performance C++

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

//display(): print supplied string on console fetching characters.
void display(char* s){
	int i = 0;
	char *temp = s;
	for (i; i < 16; ++i)
		printf("%c", *temp ? *temp : ' ');

int main()
	char source[16]="interview\0sansar";
	char str_cpy_destination[16];
	char mem_cpy_destination[16];
       //intialize buffer to 0, if not buffer will have garbage values.
	memset(str_cpy_destination, 0, 16);
	memset(mem_cpy_destination, 0, 16);

	//Display the source string.

	strcpy (str_cpy_destination,source);

	memcpy ( mem_cpy_destination, source, 16);

	return 0;

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.

Related Posts