Reputation: 945
The function definition of memcpy reads as below -
The memcpy function copies size bytes from the object beginning at from into the object beginning at to. The behavior of this function is undefined if the two arrays to and from overlap; use memmove instead if overlapping is possible.
What does arrays "to" and "from" overlap mean? When do we say two array overlap?
Usually, we think of something to be overlapping when it is of the scenario - "to" array starts at an address 1000 and has a size of 100 and "from" array starts at an address 1050 and has a size of 100.
But this can't happen, since the system does not allocate the memory for "from" array at 1050, since "to" array has been already allocated the location between 1000 to 1100.
Upvotes: 3
Views: 755
Reputation: 31389
This would be an overlap:
char arr[10];
// Code that does something
memcpy(&arr[0], &arr[3], 5);
But this would not:
memcpy(&arr[0], &arr[3], 2);
If you have two char pointers, p
and q
and you call memcpy(p, q, size)
, then an overlap means that there is at least one byte that belongs to both the interval [p,p+size]
and [q,q+size]
. In the above example, those elements are arr[3]
and arr[4]
.
Upvotes: 3