Memcpy function, memcpy
Implementation 1: high quality c ++, c Programming Guide
Void * mymemcpy (void * dst, const void * src, size_t num) {assert (dst! = NULL) & (src! = NULL); // assert (des> = src + num | src> dst + num); byte * psrc = (byte *) src; // byte is the unsigned char type. byte * pdst = (byte *) dst; while (num --> 0) * pdst ++ = * psrc ++; return dst ;}
Disadvantage: if the memory overlaps are not considered, you can add an assert (des> = src + num | src> dst + num );
Implementation 2: Consider overlap and replicate when there is overlap
void * mymemcpy(void *dest, const void *src, size_t count) { if (dest == NULL || src == NULL) return NULL; char *pdest = static_cast <char*>(dest); const char *psrc = static_cast <const char*>(psrc); int n = count; if (pdest > psrc && pdest < psrc+count) { for (size_t i=n-1; i != -1; --i) { pdest[i] = psrc[i]; } } else { for (size_t i= 0; i < n; i++) { pdest[i] = psrc[i]; } } return dest; }
Improvements to the memcpy function:
Thoughts for improvement:
Most of them think that memcpy is a copy loop from char to char, worrying about its efficiency. In fact, memcpy is the most efficient memory copy function. It is not so silly. It is used to copy one byte of memory. When the address is not aligned, it is a copy of one byte and one byte. After the address is aligned, it will be copied using the CPU length (similar to dma), 32bit or 64bit, some optimized commands will be selected based on the cpu type for copying. In general, the implementation of memcpy is related to the CPU type, operating system, and cLib. There is no doubt that it is the most efficient in the memory copy, please feel free to use it.
Void * mymemcpy (void * dst, const void * src, size_t num) {assert (dst! = NULL) & (src! = NULL); int wordnum = num/4; // calculate the number of 32 bits, copy int slice = num % 4 in 4 bytes; // The remaining int * pintsrc = (int *) src; int * pintdst = (int *) dst; while (wordnum --) * pintdst ++ = * pintsrc ++; while (slice --) * (char *) pintdst ++) = * (char *) pintsrc ++ ); return dst ;}
Reprinted from: http://blog.csdn.net/xiaobo620/article/details/7488827