implementation of memmove in c language

how to make memmove in c

The memmove is a c library function copies n characters from the source to the destination memory. In the program, we have to verify the memory overlap scenario before using the string library function to copy n characters from one memory location to other memory location.



Note: If source and destination memory overlap to each other then we should use memmove in place of strncpy or memcpy otherwise we may get the undefined result.

Some important points

  • In the case of memory overlap, we should use memmove.
  • Although memmove copy n byte from source to the destination memory, memmove slower than memcpy.
  • memmove can copy in both forward and backward direction while memcpy only copy in the forward direction.It is the basic difference between memcpy and memmove.

Syntax

Parameters

pvDestination — This is the pointer to the destination buffer, where data is to be copied.
pvSource — This is the pointer to the source buffer, from where data is to be copied.
n — Number of bytes to copy.

Return value

This function returns the pointer to the destination buffer.

See this: Difference between memcpy and memmove.

Simple program to describe how to use memmove in c

In below example, the memory of source and destination buffer is overlapped to each other.So here, I am using memmove a string function to copy the data from the source to destination buffer.

Now, let us compile the above program and run it that will produce the following result:

image

Note: In place of memmove if we used strncpy then we got undefined output.

image


How to write own memmove in c

Generally, we use the memmove function in our program, when we faced the overlapping scenario between the source and destination buffer. memmove function is slower than the memcpy so we often avoid the use of memmove.

When we create an own memmove function, then we have to make the focus on overlap scenario.To handle the overlapping scenario we just copy n byte from source buffer to a temporary buffer and after that simply copy the data from the temporary buffer to the destination buffer.

Implementation of memmove in c

Source Code 1:

Source Code 2:

Source Code 3:

Note: To remove the extra overhead we can also check the memory overlap scenario in source and destination buffer when creating the memmove function.

There is the following condition, which must be handled when creating memmove in c.

  • If the source and destination addresses are same then left as it is.
  • If the source and destination addresses overlap then copy from the end (backward copy).
  • If the source and destination addresses do not overlap then copy from the beginning (forward a copy).

overlap scenario in buffer

 

Sample program to check the created memmove function

Now, let us compile the above program and run it that will produce the following result

imag3

Leave a Reply