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);
Below is a sample C program to show the working of memmove().
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.
For example, consider below program.
Since the input addresses are overlapping, the above program overwrites the original string and causes data loss.
Consider the below program for understanding the difference between the memcpy and memmove function in case of overlapping happens.
Original string :Learningisfun memcpy overlap : LearningLearningis memmove overlap : LearningLearningLe
As you can see clearly with memmove function whenever overlap happens (i.e when the first pointer moves to the character ‘i’) then the first pointer will start to print from the beginning (output Le) but with memcpy function, it just ignores if there is an overlap and just keep moving forward.
Write your own memcpy() and memmove()?
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Rated as one of the most sought after skills in the industry, own the basics of coding with our C++ STL Course and master the very concepts by intense problem-solving.
- Write your own memcpy() and memmove()
- Iterate over characters of a string in C++
- Difference between int (*p) and int* p?
- 3-way comparison operator (Space Ship Operator) in C++ 20
- How to generate a vector with random values in C++?
- Difference between std::set vs std::vector in C++ STL
- Vector of Maps in C++ with Examples
- Data Conversion in C++
- Order of execution in initializer list in C++
- Unusual behaviour with character pointers
- Header Guard in C++
- Can we write a print statement within if parentheses?
- If memory allocation using new is failed in C++ then how it should be handled?
- Draw an ellipse divided by straight line into two colored part in C++ Graphics
Improved By : vermashobhit1994