Frage

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?

War es hilfreich?

Lösung

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.

Andere Tipps

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

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top