What is the difference between memmove and memcpy?

前端 未结 9 1715
Happy的楠姐
Happy的楠姐 2020-11-28 02:13

What is the difference between memmove and memcpy? Which one do you usually use and how?

9条回答
  •  隐瞒了意图╮
    2020-11-28 02:34

    memmove can handle overlapping memory, memcpy can't.

    Consider

    char[] str = "foo-bar";
    memcpy(&str[3],&str[4],4); //might blow up
    

    Obviously the source and destination now overlap, we're overwriting "-bar" with "bar". It's undefined behavior using memcpy if the source and destination overlap so in this case cases we need memmove.

    memmove(&str[3],&str[4],4); //fine
    

提交回复
热议问题