C Reference ยท string.h
C memmove() function
Reference for C memmove(): copy bytes between regions that may overlap, shift array elements for insert and delete, and how it differs from memcpy.
memmove() copies a block of bytes like memcpy, but it is guaranteed to work when the source and destination overlap. The result is as if the source were first copied into a temporary buffer and then from there to the destination.
That makes it the right tool for shifting data inside a single array: inserting an element, deleting one, or sliding a window of bytes.
#include <string.h> void *memmove(void *dest, const void *src, size_t n);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Syntax
void *memmove(void *dest, const void *src, size_t n);
| Name | Description |
|---|---|
dest |
Destination of the copy. May overlap the source. |
src |
Source of the copy. |
n |
The number of bytes to move. |
Returns: dest.
Errors / undefined behavior: both regions must be valid for n bytes. The destination must have room for the data, and NULL pointers are undefined even for n == 0.
Usage notes
- Use
memmovewhenever overlap is possible, andmemcpywhen it is not. Callingmemcpyon overlapping regions is undefined behavior and can appear to work for small sizes, then fail with a different compiler or optimization level. - Cost is the same order as
memcpy: linear inn. Implementations pick the copy direction (forwards or backwards) based on the addresses. - Inserting or deleting in an array is O(n) because the elements after the position move. If you do it often, consider a linked list or a gap buffer.
- Keep the terminator in mind. When shifting a string, move
strlen(...) + 1bytes so the terminator comes along, as above. - Check capacity first. Moving data to the right can write past the end of the array. Compare
len + 1with the capacity before inserting. nis in bytes: multiply an element count bysizeofthe element.- It is not
strcpy. It ignores terminators, so it is safe for binary data, but it does nothing to keep strings valid unless you move the terminator. - Overlap does not mean aliasing for types: copying between objects of different types still copies bytes only; it does not convert values.
Related
memcpy,memset,strcpyandstrncpy,realloc- Lessons: Dynamic memory, String functions