xdevel wrote:
>
Hi, anyone can make me an example where
memmove does not cause a memory overlapping and
where memcpy do it?
If you have
char array[] = "123";
then
memmove(array + 1, array, 2);
will give you a string like "112".
This function call:
memcpy(array + 1, array, 2);
is undefined. It could do anything, including bad things
that you might regret, but the two most likely outcomes
would be either identical behavior to memmove,
or a resulting string like "111".
/* BEGIN new.c */
#include <stdio.h>
#include <string.h>
#define STRING "123"
void *mem_cpy(void *s1, const void *s2, size_t n);
int main(void)
{
char array[sizeof STRING];
strcpy(array, STRING);
puts(array);
memmove(array + 1, array, 2);
puts(array);
strcpy(array, STRING);
mem_cpy(array + 1, array, 2);
puts(array);
return 0;
}
void *mem_cpy(void *s1, const void *s2, size_t n)
{
unsigned char *p1 = s1;
const unsigned char *p2 = s2;
while (n-- != 0) {
*p1++ = *p2++;
}
return s1;
}
/* END new.c */
--
pete