Simulation of memcpy and memmove functions in C Language

Source: Internet
Author: User
Tags types of functions

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.