Understanding memcpy

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.

I don't think memcpy() is designed for what you want. In general, you would use memcpy() to copy one or more whole objects (where an object might be an int, a char, a long long, etc.)

    int a[4] = { 1, 2, 3, 4 };
    int b[3];
    int c[5] = { 0 };

    ::memcpy(b, a, 3 * sizeof(int));   // b is { 1, 2, 3 }
    ::memcpy(c+2, b, 3 * sizeof(int)); // c is { 0, 0, 1, 2, 3 }

c+2 is not "c + 2 bytes". It is "c + 2 ints" (8 bytes on a Win32/x86 system).

You can access the individual bytes by casting to a char or unsigned char pointer, but I don't recommend that unless you really understand what you're doing as there are many pitfalls.

    unsigned x = 0;
    unsigned char *px = reinterpret_cast<unsigned char *>(&x);

    px[0] = 0xFF;
    px[2] = 0xAA;

One of the dangers here is that you are assuming knowledge about how the computer stores an integer. On an x86 system, x will be 0x00AA00FF but on a Sun Sparc system it will be 0xFF00AA00.

if you need to set parts of an integer it is often better to use "or" and "shift".

    x = (0xFF<<24) | (0xAA<<8);

will give you 0xFF00AA00 on any architecture. 0xFF<<24 shifts the value 0xFF by 24 bits to the left, making 0xFF000000. 0xAA<<8 shifts the value 0xAA by 8 bits to the left, making 0x0000AA00.

We "or" them together, giving 0xFF00AA00.

Tags:

C++

Memory

Memcpy