How to use and when is good use memmove in C?

前端 未结 3 1257
野的像风
野的像风 2021-02-19 12:06

I have two doubt about use of memmove():

  • When is preferable use this function instead of use another function (i.e. a created own functio
3条回答
  •  萌比男神i
    2021-02-19 12:50

    memmove is like memcpy except the destination and source array can overlap.

    With memcpy you promise that the regions are not overlapping which allows the implementation to perform some additional optimizations. So memcpy can be faster than memmove.

    The memmove function takes a void * destination argument and a const void * source argument. It means you can call the function with destination and source argument of array type because they will be converted to pointer types. And as you can assign any non-qualified object pointer types to void * or const void *, you won't need any cast when calling the function.

    char src[1024] = {0};
    char dst[1024];
    
    memmove(dst, src, sizeof dst);
    /* src and dst don't overlap you should choose memcpy instead */
    memcpy(dst, src, sizeof dst);
    

    Now it's usually better to use memcpy or memmove than to code your own function. In glibc for example, depending on the MCU instruction set and the size to copy, memcpy can be replaced by the compiler with some fast inline assembly versions of memcpy.

提交回复
热议问题