Search code examples
cmemcpymemmove

Example of using memmove in place of memcpy


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?


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.