memcpy in place array copy

Source: Internet
Author: User

First look at a piece of code

#include <stdio.h>#include<pthread.h>intMain () {intt1[Ten]; inti =0;  for(i; i<Ten; i++) {T1[i]=i; printf ("t1[%d] =%d\n", I, t1[i]); } printf ("\ n"); memcpy (&t1[0], &t1[2],5*sizeof(int)); I=0;  for(i; i<5; i++) {printf ("t1[%d] =%d\n", I, t1[i]); }    return 0;}

I ran the ubuntu16.04, and the output was:

t1[02t1[13t1[24t1[3 5 t1[46

But the same program runs on ubuntu14.04 's virtual machine, and the result is:

t1[02t1[15t1[24t1[3 5 t1[46

The copy in the Mempcy group appears to be unsafe. Further research is needed.

Different companies have different implementations of stdlib function, and copies like this memory overlap need to use API Memmove () instead of memcpy.
In principle, when memory overlaps, the content is replicated in a buffer-like place, and the contents of the buffer are overwritten with dest memory. The efficiency will be slower than memcpy.

memcpy in place array copy

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.