![]() |
VOOZH | about |
The memcpy function is used to copy a block of data from a source address to a destination address. It assumes the memory regions do not overlap.
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.
Copied string is GeeksforGeeks Copied array is 10 20 30 40 50
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.
Example of Failure:
Output:
GeeksGeeksGeek
Since the input addresses are overlapping, the above program overwrites the original string and causes data loss.
Output:
GeeksGeeksfor
While a common trick is to use a temp array instead of directly copying from src to dest to handle overlapping addresses, this is inefficient. A professional implementation avoids double copies by picking the direction of the copy based on the relative positions of src and dest.
GeeksGeeksfor
Note: Further speed can be achieved by copying by word size (e.g., 4 or 8 bytes at a time) or using vector instructions for contiguous memory blocks.