Simulation of memcpy and memmove functions in C Language
Here, the simulation implementation of memcpy and memmove functions requires the use of a null pointer to pass the parameter, and then forced type conversion to char type, using the size_t macro to accept the offset, the simulation implementation is as follows: memcpy functions:
Void * my_memcpy (void * dst, const void * src, size_t count) {assert (dst); assert (src); void * ret = dst; while (count --) {* (char *) dst = * (char *) src; dst = (char *) dst + 1; src = (char *) src + 1;} return ret ;}
Memmove function: The memmve function is used to avoid Memory overlap (as mentioned in the previous article) of the memcpy function. The idea of the new function is that if there is memory overlap, then we copy from the back to the front. If not, just like memcpy, we copy from the back to the back. The implementation code is as follows:
Void * my_memmove (void * dst, const void * src, size_t count) {assert (dst); assert (src); void * ret = dst; if (char *) dst> (char *) src + count) // determines whether memory overlaps {while (count --) {* (char *) dst + count) = * (char *) src + count) ;}} else {while (count --) {* (char *) dst = * (char *) src; dst = (char *) dst + 1; src = (char *) src + 1 ;}} return ret ;}
For memory copying, a copy offset parameter is transferred more than the string copy parameter, because the copy of a string is often stopped when there is 0, and there is no such problem in memory copying, using these two types of functions requires you to think about how to efficiently run the program.