memmove() in C/C++

Last Updated : 7 Mar, 2026

memmove() is used to copy a block of memory from a location to another. It is declared in string.h

// Copies "numBytes" bytes from address "from" to address "to"
void * memmove(void *to, const void *from, size_t numBytes);
C
#include <stdio.h>
#include <string.h>

int main()
{
    char str1[] = "Geeks"; 
    char str2[] = "Quiz"; 

    puts("str1 before memmove ");
    puts(str1);

    /* Copies contents of str2 to sr1 */
    memmove(str1, str2, sizeof(str2));

    puts("\nstr1 after memmove ");
    puts(str1);

    return 0;
}

Output
str1 before memmove 
Geeks

str1 after memmove 
Quiz

How is it different from memcpy()?

memcpy() simply copies data one by one from one location to another. On the other hand memmove() copies the data first to an intermediate buffer, then from the buffer to destination.
memcpy() leads to problems when strings overlap. 

C
#include <stdio.h>
#include <string.h>
int main()
{
    char csrc[100] = "Geeksfor";
    memcpy(csrc + 5, csrc, strlen(csrc) + 1);
    printf("%s", csrc);
    return 0;
}

Output
GeeksGeeksfor

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

C
#include <stdio.h>
#include <string.h>

int main()
{
    char str1[100] = "Learningisfun";
    char str2[100] = "Learningisfun";

    printf("Original string (str1) : %s\n", str1);
    printf("Original string (str2) : %s\n", str2);

    // Using memcpy on first copy
    memcpy(str1 + 8, str1, 10);
    printf("memcpy overlap  : %s\n", str1);

    // Using memmove on second independent copy
    memmove(str2 + 8, str2, 10);
    printf("memmove overlap : %s\n", str2);

    return 0;
}

Output
Original string :Learningisfun
 memcpy overlap : LearningLearningis
 memmove overlap : LearningLearningLe
 

Both functions are tested on separate copies of the same original string. When memory regions overlap, memcpy() exhibits undefined behavior and may produce incorrect or corrupted output, whereas memmove() handles overlapping safely by copying the data in a way that preserves the original content, resulting in the expected and correct output.

Write your own memcpy() and memmove()

Comment