VOOZH about

URL: https://www.geeksforgeeks.org/cpp/write-memcpy/

⇱ Write your own memcpy() and memmove() - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Write your own memcpy() and memmove()

Last Updated : 18 Feb, 2026

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.


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

Example of Failure:

  • Source: "Geeksfor"
  • Action: memcpy(src + 5, src, 8)
  • Result: "GeeksGeeksGeek" (Data loss due to overwriting)

Output:

GeeksGeeksGeek

Since the input addresses are overlapping, the above program overwrites the original string and causes data loss. 

Output:

GeeksGeeksfor

Implementing memmove()

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.

  • Forward Copy: If the destination is before the source, start from the beginning.
  • Backward Copy: If the destination is after the source, start from the end to avoid overwriting the source data.

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

Comment
Article Tags: