简体   繁体   中英

c++ memcpy error

I would like to copy 2 ints, 2 shorts and 1 char one after the other.

This is what I did:

int32_t a=1;
int32_t b=2;
int16_t c=3;
int16_t d=4;
int8_t e=5;
char*buf=new char[104];
memcpy(buf, &a, 32);
memcpy(buf + 32, &b, 32);
memcpy(buf + 64, &c, 16);
memcpy(buf + 80, &d, 16);
memcpy(buf + 96, &e, 8);

Is this correct ? My debugger says that the third line affects the second, but maybe I'm just misusing my debugger (more specifically, it says that the value of *((int32_t*)(buf+32)) changed between the second and third memcpy).

Thanks.

You've conflated bits and bytes and are overreading and overwriting large sections of memory!

int32_t x; /* 4 bytes, 32 bits */
int16_t y; /* 2 bytes, 16 bits */

memcpy(buf            , &x, sizeof(x)); /* copy 4 BYTES, or sizeof(x) */
memcpy(buf + sizeof(x), &y, sizeof(y)); /* copy 2 bytes */

So, your buffer is about 8 times larger than it needs to be, and you're copying 4 times as much data as needed every time.

memcpy measures size in bytes, not bits. It should be:

memcpy(buf, &a, 4);
memcpy(buf + 4, &b, 4);
memcpy(buf + 8, &c, 2);
memcpy(buf + 10, &d, 2);
memcpy(buf + 12, &e, 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM