Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding memcpy

Tags:

c++

memory

memcpy

int a = 10;
int* pA = &a;
long long b = 200;
long long* pB = &b;

memcpy (pB,pA,4);
memcpy (pB+1,pA,4);

cout<<"I'm a memcpy!: "<<*(pB)<<endl;

I'm doing some tests with memcpy to teach myself how memory works. What I am trying to do is make b = to "1010". I can copy the value from a to b, but then I try to offset the memory by 1 byte and write another 10 but it doesn't work it only outputs "10".

What would I need to do to get a value of 1010?

like image 908
Greg G Avatar asked Jun 13 '12 23:06

Greg G


1 Answers

A few problems with your code as it stands:

  • You copy 4 bytes, but the destination is type int. Since int is not guaranteed to be any particular size, you need to make sure that it is at least 4 bytes long before you do that sort of memcpy.
  • memcpy works on the byte level, but integers are a series of bytes. Depending on your target architecture, the bytes within an integer may be arranged differently (big-endian, little-endian, etc). Using memcpy on integers may or may not do what you expect. It's best to use byte arrays when learning how memcpy and friends work.
  • Your second memcpy uses pB+1 as the target. This doesn't advance the pointer one byte, it advances it by sizeof(*pB) bytes. In this case, that leaves it pointing to an invalid address (past the end of the variable). This call to memcpy will corrupt random memory, which can crash your program or cause unpredictable results.
like image 147
bta Avatar answered Sep 20 '22 17:09

bta