c++ memset/sizeof怪异的字符缓冲区

c++ memset/sizeof weirdness with char buffer

本文关键字:字符 缓冲区 memset sizeof c++      更新时间:2023-10-16

两个独立的程序运行几乎相同的代码。我正在将int, enum和4个浮点数复制到unsigned char缓冲区中,然后将它们读取回来以确保过程是正确的。

第一个是一个简单的测试程序,可以在这里找到。

输出如下:

id: 10
o: 2
one: 1
two: 2
three: 3
four: 4
---
id: 10
o: 2
one2: 1
two2: 2
three2: 3
four2: 4

所以我想,好吧…我可以把它移到实际的程序中。主程序可以在这里找到。几乎一样,对吧?这里有一个问题:从缓冲区读取回变量是软管的:

id: 1
o: 1
p1x: 1
p1y: 2
p2x: 3
p2y: 4
---
id: 1
o: 1073741824
one: 3
two: 4
three: 2.76624e+19
four: 4

由于某些原因,当值被读出时…memcpy改变了多个变量的值,我最终搞砸了:

memcpy(&i2,&buffer[0],4);      //sets i2 correctly to 1
memcpy(&o2, &buffer[4],4);     //sets o2 correctly to DISTANCE (enum == 1)
memcpy(&one,&buffer[8],8);     //resets o2 to 1073741824 and one to 1
memcpy(&two,&buffer[16],8);    //sets two correctly to number 2, but one to 3
memcpy(&three,&buffer[24],8);  //sets three correctly to 3, but two to 4
memcpy(&four,&buffer[32],8);   //sets three to 2.766... and four to 4
std::cout << "id: " << i2 << std::endl;
std::cout << "o: " << o2 << std::endl;
std::cout << "one: " << one << std::endl;
std::cout << "two: " << two << std::endl;
std::cout << "three: " << three << std::endl;
std::cout << "four: " << four << std::endl;

使用sizeof()修复:

memcpy(&i2,&buffer[0],sizeof(i2));     
memcpy(&o2, &buffer[4],sizeof(o2));     
memcpy(&one,&buffer[8],sizeof(one));     
memcpy(&two,&buffer[16],sizeof(two));    
memcpy(&three,&buffer[24],sizeof(three));  
memcpy(&four,&buffer[32],sizeof(four));
----
id: 1
o: 1
p1x: 1
p1y: 2
p2x: 3
p2y: 4
---
id: 1
o: 1
one: 1
two: 2
three: 3
four: 4
这里到底发生了什么?

您的错误是硬编码float大小为8,而它可能是4。因此,从缓冲区中读取8字节到浮点数会得到未定义的行为。

使用sizeof()修复它,因为它正确返回4。