C Language — making memmove()

Márcia Mota
2 min readFeb 2, 2021

--

The function memmove is included in the string.h library.

memmove() copies a number of bytes from a block of memory to a destination. Those areas of memory may overlap but data loss must be prevented. It returns a pointer to the destination block of memory.

void *memmove(void *dest, const void *src, size_t n)
{
char *cdest;
char *csrc;
cdest = (char *)dest;
csrc = (char *)src;

If the destination point in memory (dest) is before/less than the source block of memory (src), the copy will work as expected. Even if the copied bytes overlaps the beginning of the src block, that specific data has already been copied to the dest block (image 1).

if (dest <= src)
{
while(n--)
{
*cdest++ = *csrc++;
}
}
else if (dest > src)
{
cdest += n - 1;
csrc += n - 1;
while(n--)
{
*cdest-- = *csrc--;
}
}
return (dest);
}

If dest is after/more than src, to ensure that no data loss occurs (image 2), the copy must start from the last byte to be copied (image 3). To find the last byte of src and dest add the number of bytes to be copied (n), minus 1 (to exclude the ‘\0' characters that signalizes the end of a string).

if(!dest && !src)
return(0);

We also need to ensure that if both src and dest are empty the return will be NULL.

--

--

Responses (2)