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?

有帮助吗?

解决方案

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.

其他提示

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().

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top