C Library & Correctnessfoundational
When do you use memmove() instead of memcpy() in C? Describe why.
0 upvotes
Practice with AISoon
Use memmove() whenever the source and destination regions may overlap; use memcpy() only when you can guarantee they do not overlap.
Both have the signature void *f(void *dest, const void *src, size_t n) and copy n bytes. The critical difference is defined behavior under overlap:
memcpy()has undefined behavior if the regions overlap. It is permitted to copy in any order (forward, backward, in word-sized blocks, vectorized, etc.) and may read a source byte after it has already been overwritten, corrupting the result. The trade-off is that, free from the overlap requirement, it can be maximally fast.memmove()is guaranteed correct even when regions overlap. It behaves as if the source were first copied into a temporary buffer and then into the destination. In practice implementations don't allocate a temp buffer — they detect direction and copy forward whendest < srcor backward whendest > src, so no byte is read after being clobbered.
Classic example — shifting an array down by one element (overlapping):
c
int a[5] = {1, 2, 3, 4, 5};/* shift left by one: dest=a, src=a+1, regions overlap */memmove(a, a + 1, 4 * sizeof(int)); /* correct -> {2,3,4,5,5} *//* memcpy(a, a+1, 4*sizeof(int)); <-- UB, may corrupt */
Rule of thumb: if you cannot prove the buffers are disjoint (e.g., sliding window buffers, in-place insert/delete, ring buffers, overlapping image rows), reach for memmove. memcpy is the right default only for known-disjoint copies (separate buffers, struct copies) where you want the speed.
