当我们不考虑一块内存的具体内容与类型,而需要进行拷贝时,我们经常会用到memcpy或者memmove,
memcpy和memmove()都是C语言中的库函数,在头文件string.h中,作用是拷贝一定长度的内存的内容,原型分别如下:
void *memcpy(void *dst, const void *src, size_t count);
void *memmove(void *dst, const void *src, size_t count);
他们的作用是一样的,唯一的区别是,当内存发生局部重叠的时候,memmove保证拷贝的结果是正确的,memcpy不保证拷贝的结果的正确。但是在VC++或者VS的编译器上,memcpy也处理了这个问题,在GCC上没有处理这个问题。
/*
filename: memcpy.c
author: caocun
*/
#include<stdio.h>
#include<string.h>
#include<memory.h>
//在VC++编译环境下,对于.c文件,则声明变量需要在最前面。
//内存拷贝的可能情况:
/*
(1)内存低端 <-----s-----> <-----d-----> 内存高端 start at end of s
(2)内存低端 <-----s--<==>--d-----> 内存高端 start at end of s
(3)内存低端 <-----sd-----> 内存高端 do nothing
(4)内存低端 <-----d--<==>--s-----> 内存高端 start at beginning of s
(5)内存低端 <-----d-----> <-----s-----> 内存高端 start at beginning of s
*/
void* mymemcpy(void* dest, void* source, size_t count)
{
char *ret =(char *)dest;
char *r = ret;
char *s = (char *)source;
unsigned int i=0;
if(NULL == dest || NULL == source
|| count<=0 || dest == source) return NULL;
count = (count>strlen(s)) ? strlen(s):count;
while(count--)
{
*r++ = *s++;
}
return ret;
}
void *mymemmove(void *dest,const void *source,size_t count)
{
char *ret =(char *)dest;
char *r = ret;
char *s = (char *)source;
unsigned int i=0;
if(NULL == dest || NULL == source
|| count<=0 || dest == source) return NULL;
count = (count>strlen(s)) ? strlen(s):count;
if(r<=s || r>=s+count)
{
while(count--)
{
*r++ = *s++;
}
}
else
{
//从后往前拷贝
r = (char *)dest+count-1;
s= (char *)source+count-1;
while(count--)
{
*r-- = *s--;
}
}
return ret;
}
int main()
{
char dest[40] = {"hello, world"};
char *ptr = NULL;
/
ptr = (char*)memcpy(dest+5, dest, 15);
printf("ptr = %s\n", ptr);
printf("dest = %s\n", dest);
//
return 0;
}