memcpy与memmove的区别及源码

       当src和dst区域没有重叠时,两个函数是完全一样的。没有重叠的条件是: dst <= src || (char *)dst >= ((char *)src + count 。否则,memcpy是不能正常工作的,memmove是可以正常工作的。


memcpy函数

       void *memcpy(void *dest, const void *src, size_t n);

DESCRIPTION

       The  memcpy()  function copies n bytes from memory area src to memory area dest.  The memory areas should not overlap.  Use memmove(3)

       if the memory areas do overlap.

       memcpy函数的功能是从源src所指的内存地址的起始位置开始拷贝n个字节到目标dest所指的内存地址的起始位置中。


memcpy实现代码

void * __cdecl memcpy ( void * dst,const void * src,size_t count)
{
    void * ret = dst;
    while (count--)
    { 
        // 注意, memcpy函数没有处理dst和src区域是否重叠的问题
        *(char *)dst = *(char *)src;
        dst = (char *)dst + 1;
        src = (char *)src + 1;
    }
    return(ret);
}

memmove函数

       void *memmove(void *dest, const void *src, size_t n);

DESCRIPTION
       The  memmove() function copies n bytes from memory area src to memory area dest.  The memory areas may overlap: copying takes place as
       though the bytes in src are first copied into a temporary array that does not overlap src or dest, and the bytes are then copied  from
       the temporary array to dest.

       memmove用于从src拷贝n个字符到dest,如果目标区域和源区域有重叠的话,memmove能够保证源串在被覆盖之前将重叠区域的字节拷贝到目标区域中。但复制后src内容会被更改。但是当目标区域与源区域没有重叠则和memcpy函数功能相同。


memmove实现代码

void * __cdecl memmove ( void * dst,const void * src,size_t count)
{
    void * ret = dst;
    if (dst <= src || (char *)dst >= ((char *)src + count))
    {
        // 若dst和src区域没有重叠,则从起始处开始逐一拷贝
        while (count--)
        {
            *(char *)dst = *(char *)src;
            dst = (char *)dst + 1;
            src = (char *)src + 1;
        }
    }
    else
    {// 若dst和src 区域交叉,则从尾部开始向起始位置拷贝,这样可以避免数据冲突
        dst = (char *)dst + count - 1;
        src = (char *)src + count - 1;
        while (count--)
	    {
			*(char *)dst = *(char *)src;
			dst = (char *)dst - 1;
			src = (char *)src - 1;
	    }
    }
    return(ret);

}

memset函数

NAME

       memset - fill memory with a constant byte

SYNOPSIS

       #include

       void *memset(void *s, int c, size_t n);

DESCRIPTION

       The memset() function fills the first n bytes of the memory area pointed to by s with the constant byte c.

RETURN VALUE

       The memset() function returns a pointer to the memory area s.

memset函数一般用于对内存的初始化,在这里需要注意的是,memset函数是对内存中的每个字节(按字节)设置成c的值。

	int *pint = NULL;

	pint = (int*)malloc(sizeof(int));
	if (pint == NULL)
	{
		return 0;
	}
	memset(pint, 1, sizeof(int));
查看pint所值内存值为



你可能感兴趣的:(C语言基础)