Question

Difference: If there is an overlap, use memmove in place of memcpy

Q: Could you provide a practical scenario of any C lib function where an overlap happens so memmove is used in place of memcpy?

Was it helpful?

Solution

Here's one:

// len => array length, idx => index where we want to remove
void removeAt(int* array, size_t* len, size_t idx)
{
    // copy next values to replace current
    // example: {1, 2, 3, 4} => {1, 3, 4}
    //              ^ remove
    memmove(&array[idx], &array[idx+1], (--(*len) - idx) * sizeof(int));
}

Edit: Regarding this appearing in the implementation of a C stdlib function, that would be a bit more difficult to find, since each implementation can do their own thing, and most stdlib functions require that the arguments do not overlap.

OTHER TIPS

For example you need to insert an element in the middle of an array (in-place). This requires shifting the elements from the insertion points onwards by one place. This can be done with memmove() but not with memcpy().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top