c++ memset/sizeof怪异的字符缓冲区
c++ memset/sizeof weirdness with char buffer
两个独立的程序运行几乎相同的代码。我正在将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。
相关文章:
- C++字符*缓冲区的大小
- 将字符缓冲区强制转换为函数指针
- 来自无符号字符缓冲区的虚拟输出
- 如何在C++中将无符号字符缓冲区转换为双精度?
- 如何使 printf 以与 NSLog 相同的方式打印字符缓冲区?
- 将字符缓冲区转换为字符串
- 读取文件时字符缓冲区溢出
- 来自字符缓冲区的恐惧
- 为什么在我的测试程序中,从字符缓冲区读取一个int时,"std::copy"5x(!)比"
- C/C++ 从字符缓冲区读取以填充结构
- 具有输入无符号字符缓冲区C++的设备 IoControl
- 如何从字符 * 缓冲区中的位置 y 读取 x 个字符
- 从字符 * 缓冲区到 wchar_t * 缓冲区的内存
- 如何将字符 * 缓冲区转换为无符号的短 int * bufferSh
- 将windows BITMAP转换为PIX(无符号字符缓冲区)
- RAII字符缓冲区
- MFC-传递带有PostMessage From DLL的字符缓冲区
- 如何使用Gstreamer播放原始字符*缓冲区
- 在 Win32 中解析巨大的字符* 缓冲区
- 分配字符缓冲区以保存浮点的文本表示形式