2

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?

abligh
  • 24,573
  • 4
  • 47
  • 84
codey modey
  • 983
  • 2
  • 10
  • 23

2 Answers2

3

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

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • that is an acceptable, general scenario, but do you remember any from a library function? – codey modey Feb 23 '14 at 21:08
  • @codeymodey: Have a browse of http://code.ohloh.net/search?s=memmove&pp=0&fe=c&mp=1&ml=1&me=1&md=1&ff=1&filterChecked=true -- there's a ton of real-world examples there. – NPE Feb 23 '14 at 21:11
  • @codeymodey: Here's an example from the Linux kernel: http://code.ohloh.net/file?fid=LACPbnMYI2RxpXmGAuL1H08qbKk&cid=6NGO2C2fa5k&s=memmove&pp=0&fp=306559&fe=c&ff=1&filterChecked=true&mp=0&ml=1&me=1&md=1#L37 – NPE Feb 23 '14 at 21:13
3

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.

Tim Čas
  • 10,501
  • 3
  • 26
  • 32