I am trying to replicate the memmove function. I copied the following from online, and it's replicating the memmove function. But I am wondering, why we are checking source and destination memory addresses (if statement)? why that check is needed? is there any chance for overlap? If yes, how the destination and source string will overlap? memmove function has to copy the source string to the destination string in a non-destructive manner. Since both are stored in a different memory address how do both inrfere? where does the destruction happen?
void *ft_memmove(void *dst, const void *src, size_t len)
{
char *dst_aux;
char *src_aux;
char *dst_last;
char *src_last;
if (!dst && !src)
return (NULL);
dst_aux = (char *)dst;
src_aux = (char *)src;
if (dst_aux < src_aux)
while (len--)
*dst_aux++ = *src_aux++;
else
{
dst_last = dst_aux + (len - 1);
src_last = src_aux + (len - 1);
while (len--)
*dst_last-- = *src_last--;
}
return (dst);
}
Bhavesh RavalPosted Oct 23, 2023, 12:23 PM
memmoveis a C standard library function used to copy a block of memory from one location to another. It's similar to thememcpyfunction, but it's designed to handle overlapping memory areas. In other words,memmoveis used when the source and destination memory regions can overlap without causing issues.The syntax for
memmoveis:void *memmove(void *dest, const void *src, size_t n);
destis a pointer to the destination memory buffer where the data will be copied.srcis a pointer to the source memory buffer from which the data will be copied.nis the number of bytes to copy.memmoveensures that the data is copied in a way that is safe even if the source and destination memory regions overlap. It achieves this by using a temporary buffer to perform the copy.Here's an example of how you might use
memmove:#include
#include
int main() {
char str[] = "Hello, World!";
memmove(str + 7, str, 7);
printf("%s\n", str);
return 0;
}
In this example,
memmoveis used to move the string "World!" within the same character arraystr. The function safely handles the overlap between the source and destination, resulting in "Hello, World!" as the output. If you were to usememcpyin this case, it might not work correctly due to the overlap.