Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4008489
  • 博文数量: 536
  • 博客积分: 10470
  • 博客等级: 上将
  • 技术积分: 4825
  • 用 户 组: 普通用户
  • 注册时间: 2006-05-26 14:08
文章分类

全部博文(536)

文章存档

2024年(3)

2021年(1)

2019年(1)

2017年(1)

2016年(2)

2013年(2)

2012年(10)

2011年(43)

2010年(10)

2009年(17)

2008年(121)

2007年(252)

2006年(73)

分类:

2007-08-20 11:54:50

What's the difference between memcpy and memmove?

memmove offers guaranteed behavior if the memory regions pointed to by the source and destination arguments overlap. memcpy makes no such guarantee, and may therefore be more efficiently implementable. When in doubt, it's safer to use memmove.

It seems simple enough to implement memmove; the overlap guarantee apparently requires only an additional test:

void *memmove(void *dest, void const *src, size_t n)
{
    register char *dp = dest;
    register char const *sp = src;
    if(dp < sp) {
        while(n-- > 0)
            *dp++ = *sp++;
    } else {
        dp += n;
        sp += n;
        while(n-- > 0)
            *--dp = *--sp;
    }

    return dest;
}



The problem with this code is in that additional test: the comparison (dp < sp) is not quite portable (it compares two pointers which do not necessarily point within the same object) and may not be as cheap as it looks. On some machines (particularly segmented architectures), it may be tricky and significantly less efficient [footnote] to implement.

from:
阅读(1849) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~