The differences between C/C ++ memmove and memcpy and the implementation of memmovemememcpy
1. differences from the string function strcpy:
- Both memcpy and memmove can copy any content to the memory, while strcpy only operates on strings.
- Memcpy and memmove are controlled by the third parameter, while strcpy stops copying to '\ 0.
2. Function Description:
3. Copy:
The specific copying process can be divided into three types based on the dst memory region and the src memory region:
1. When the src memory region and dst memory region do not overlap at all
2. When the src memory region and dest memory region overlap, and the dst region is before the src Region
3. When the src memory region overlaps with the dst memory region, and the src region is before the dst Region
In the above three cases, memcpy can successfully copy the first two. In the third case, the original src content is overwritten when copying the first two bytes of dst, therefore, an error occurs in the next copy. In the third case, memmove copies N Bytes from the end of src to avoid overwriting the original content.
4. Code Implementation
Memcpy:
Void * _ memcpy (void * dest, const void * src, size_t count) {assert (src! = Nullptr & dest! = Nullptr); // determines whether the dest pointer and src pointer are null. If it is null, an exception char * tmp_dest = (char *) dest; const char * tmp_src = (const char *) is thrown *) src; // convert the pointer dest and pointer src from void to char, // make each copy of a byte in the memory while (count --) * tmp_dest ++ = * tmp_src ++; return dest ;}
Memmove:
Void * _ memmove (void * dest, const void * src, size_t count) {assert (src! = Nullptr & dest! = Nullptr); // determines whether the dest pointer and src pointer are null. If it is null, an exception char * tmp_dest = (char *) dest; const char * tmp_src = (const char *) is thrown *) src; if (tmp_src <tmp_dest) // when the src address is smaller than the dest address, copy the while (count --) * tmp_dest ++ = * tmp_src ++; else if (tmp_src> tmp_dest) // when the src address is greater than the dest address, copy from the back {tmp_src + = count-1; tmp_dest + = count-1; while (count --) * tmp_dest -- = * tmp_src;} // else (tmp_src = tmp_dest) at this time, no operation is performed return dest ;}
If any error occurs, please point it out. Thank you.
CSDN address: http://blog.csdn.net/lyl_312/article/details/51419822