内存拷贝的实现.c

/*memcpy函数的实现 *memcpy是内核提供的机制,应用C编写(linux内核由C编写) *strcpy只提供字符串的拷贝,memcpy可以实现任意类型的拷贝 */
# include# include
void* Memcpy(void *dst, const void *src, int len) //destination 目的 source 源 length 长度 该长度按字节算,一个int为len = 4 { char *psrc; char *pdst; if(dst == NULL || src =https://www.it610.com/article/= NULL || len == 0) //dst需提前申请内存 { printf("内存错误!\n"); return NULL; } if((src < dst) && (char *)src + len > (char *)dst) //判断内存空间是否重叠,srcdst即有重叠(src与dst必须以字节为单位) { printf("\033[31m001\033[0m"); psrc = https://www.it610.com/article/(char *)src + len - 1; //psrc指向src的末尾 pdst = (char *)dst + len - 1; while(len--){ *pdst-- = *psrc--; //从后向前复制 } } else { printf("\033[32m002\033[0m"); psrc = https://www.it610.com/article/(char *)src; //psrc指向src的起始位 pdst = (char *)dst; while(len--) { *pdst++ = *psrc++; //从前向后复制 } } return dst; } void show(int* arrary,int n){ for (int i = 0; i int buf3[10] = {9,8,7,6,5,4,3,2,1,0}; int* buf4 = (int*)malloc(sizeof(int[10])); int* buf5 = (int*)malloc(sizeof(int[5])); int buf6[20] = {0,}; Memcpy(buf4, buf3, 40); printf("buf4 : "); show(buf4,10); Memcpy(buf5, buf3, 20); printf("buf5 : "); show(buf4,5); free(buf4); free(buf5); Memcpy(buf6, buf3, 40); printf("buf6 : "); show(buf6,10); Memcpy(buf6+4,buf6,40); printf("buf7 : "); show(buf6,10); return 0; }

    推荐阅读