A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
memmove copies n bytes from source to destination, correctly handling the case where the regions overlap. It does this by copying to a temporary buffer or by choosing the copy direction based on the relative addresses. The result is as if the source bytes were first saved and then written to the destination. memcpy makes no such guarantee. If you are not certain the regions are disjoint, use memmove. The performance difference is negligible on modern implementations.
#include <stdio.h>#include <string.h>int main(void) {char buf1[] = "ABCDEFGHIJ";char buf2[] = "ABCDEFGHIJ";printf("Original: %s\n", buf1);memmove(buf1 + 2, buf1, 5);printf("memmove +2: %s\n", buf1);char buf3[] = "ABCDEFGHIJ";memmove(buf3, buf3 + 2, 5);printf("memmove -2: %s\n", buf3);return 0;}
Shifting right by 2: the first five bytes ABCDE are copied to positions 2-6. The overlap is handled correctly. Shifting left by 2: bytes starting at position 2 (CDEFG) are copied to positions 0-4. Both directions work. With memcpy, at least one of these would produce corrupted output because the copy would overwrite source bytes before they are read.
#include <stdio.h>#include <string.h>int main(void) {int arr[10] = {1, 2, 3, 4, 5, 0, 0, 0, 0, 0};int used = 5;int insert_pos = 2;int new_value = 99;memmove(&arr[insert_pos + 1], &arr[insert_pos],(used - insert_pos) * sizeof(int));arr[insert_pos] = new_value;used++;printf("After insert at index %d: ", insert_pos);for (int i = 0; i < used; i++) {printf("%d ", arr[i]);}printf("\n");return 0;}
The elements from index 2 onward are shifted right by one position to make room for the new value. The regions overlap: the destination starts one element after the source. memmove handles this correctly. A manual loop would also work, but memmove is a single call and the compiler can optimize it to a block move instruction.
memmove is the safe default for memory copies where you are not sure about overlap. The performance cost is minimal. The correctness guarantee is absolute. When in doubt, memmove. Next: sizeof, the compile-time operator that tells you how much memory a type or expression occupies.
Finish the lesson once you have worked through the material. This awards ★ 30 XP.