Namespaces
Variants
Views
Actions

memmove, memmove_s

From cppreference.com
< c‎ | string‎ | byte
Defined in header <string.h>
void* memmove( void* dest, const void* src, size_t count );
(1)
errno_t memmove_s(void *dest, rsize_t destsz, const void *src, rsize_t count);
(2) (since C11)
1) Copies count characters from the object pointed to by src to the object pointed to by dest. Both objects are interpreted as arrays of unsigned char. The objects may overlap: copying takes place as if the characters were copied to a temporary character array and then the characters were copied from the array to dest.
2) Same as (1), except when detecting the following errors at runtime, it zeroes out the entire destination range [dest, dest+destsz) (if both dest and destsz are valid) and calls the currently installed constraint handler function:
  • dest or src is a null pointer
  • destsz or count is greater than RSIZE_MAX
  • count is greater than destsz (buffer overflow would occur)
As all bounds-checked functions, memmove_s is only guaranteed to be available if __STDC_LIB_EXT1__ is defined by the implementation and if the user defines __STDC_WANT_LIB_EXT1__ to the integer constant 1 before including string.h.

Contents

[edit] Parameters

dest - pointer to the memory location to copy to
destsz - max number of bytes to modify in the destination (typically the size of the destination object)
src - pointer to the memory location to copy from
count - number of bytes to copy

[edit] Return value

1) Returns a copy of dest
2) Returns zero on success and non-zero value on error. Also on error, if dest is not a null pointer and destsz is valid, writes destsz zero bytes in to the destination array.

[edit] Notes

memmove may be used to set the effective type of an object obtained by an allocation function.

Despite being specified "as if" a temporary buffer is used, actual implementations of this function do not incur the overhead or double copying or extra memory. A common approach (glibc and bsd libc) is to copy bytes forwards from the beginning of the buffer if the destination starts before the source, and backwards from the end otherwise, with a fall back to the more efficient memcpy when there is no overlap at all.

[edit] Example

#include <stdio.h>
#include <string.h>
 
int main(void)
{
    char str[] = "1234567890";
    puts(str);
    memmove(str+4, str+3, 3); // copy from [4,5,6] to [5,6.7]
    puts(str);
}

Output:

1234567890
1234456890

[edit] References

  • C11 standard (ISO/IEC 9899:2011):
  • 7.24.2.2 The memmove function (p: 363)
  • K.3.7.1.2 The memmove_s function (p: 615)
  • C99 standard (ISO/IEC 9899:1999):
  • 7.21.2.2 The memmove function (p: 326)
  • C89/C90 standard (ISO/IEC 9899:1990):
  • 4.11.2.2 The memmove function

[edit] See also

copies one buffer to another
(function) [edit]
copies a certain amount of wide characters between two, possibly overlapping, arrays
(function) [edit]
C++ documentation for memmove