ft_memmove
Subject
Understandable explanation
The memmove()
function does the same thing as the memcpy()
function but this time, the copy is made, as said in the man, in a non-destructive manner. This means that both strings (src and dst) can overlap in memory and this function does not overwrite part of, or the entirety of the string when making the copy.
What is memory overlapping ?
I found a really good explanation on stackexchange.com so I'll copy it here to explain what is memory overlapping.
Suppose we have an array of 5 chars, where each char is a byte long
Now according to the man page of
memcpy
, it takes 3 arguments, a pointer to the destination block of memory, a pointer to the source block of memory, and the size of bytes to be copied.What if the destination is
0x102
, the source is0x100
and the size is3
? Memory overlapping happens here. That is,0x100
would be copied into0x102
,0x101
would be copied into0x103
and0x102
would be copied into0x104
.Notice that we first copied into
0x102
then we copied from0x102
which means that the value which was originally in0x102
was lost as we overwrote it with the value we copied into0x102
before we copy from it. So we would end up with something likeInstead of
How does a function like
memmove
take care of memory overlapping ?According to its man page, it first copies the bytes to be copied into a temporary array then pastes them into the destination block as oppose to a function like
memcpy
which copies directly from the source block to the destination block.
That's for memory overlapping, it is also said that memmove
copies the bytes to be copied into a temporary array then pastes them into the destination block. That's not the way I did it because as said in the subject of the LIBFT, we can't use malloc()
for this function.
The way I did it without using malloc()
, is to first check if the 2 memory blocks are overlapping or not. If they are overlapping we'll copy from the end of the source memory block until the start. If they are not overlapping we'll copy "normally", from start to end.
Hints
ft_memmove
Commented solution
Last updated
Was this helpful?