The memcpy function is used to copy a block of data from a source address to a destination address. Below is its prototype.
void * memcpy(void * destination, const void * source, size_t num);
The idea is to simply typecast given addresses to char *(char takes 1 byte). Then one by one copy data from source to destination. Below is implementation of this idea.
Copied string is GeeksforGeeks Copied array is 10 20 30 40 50
What is memmove()?
memmove() is similar to memcpy() as it also copies data from a source to destination. memcpy() leads to problems when source and destination addresses overlap as memcpy() simply copies data one by one from one location to another. For example consider below program.
Since the input addresses are overlapping, the above program overwrites the original string and causes data loss.
How to implement memmove()?
The trick here is to use a temp array instead of directly copying from src to dest. The use of temp array is important to handle cases when source and destination addresses are overlapping.
The algorithm is inefficient (and honestly double the time if you use a temporary array). Double copies should be avoided unless if it is really impossible.
In this case though it is easily possible to avoid double copies by picking a direction of copy. In fact this is what the memmove() library function does.
By comparing the src and the dst addresses you should be able to find if they overlap.
– If they do not overlap, you can copy in any direction
– If they do overlap, find which end of dest overlaps with the source and choose the direction of copy accordingly.
– If the beginning of dest overlaps, copy from end to beginning
– If the end of dest overlaps, copy from beginning to end
– Another optimization would be to copy by word size. Just be careful to handle the boundary conditions.
– A further optimization would be to use vector instructions for the copy since they’re contiguous.
This article is contributed by Saurabh Jain. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- memmove() in C/C++
- memcpy() in C/C++
- Write a URL in a C++ program
- Write a C program that won't compile in C++
- When should we write our own copy constructor?
- How to write your own header file in C?
- When should we write our own assignment operator in C++?
- Write a program that produces different results in C and C++
- C program to write an image in PGM format
- How to write a running C code without main()?
- Read/Write structure to a file in C
- Write a C macro PRINT(x) which prints x
- Write a C program that does not terminate when Ctrl+C is pressed
- Write one line functions for strcat() and strcmp()
- Write your own strlen() for a long string padded with '\0's
Improved By : SwatiGangwar