【问题标题】:c++ memset/sizeof weirdness with char buffer [closed]c ++ memset / sizeof怪异与char缓冲区[关闭]
【发布时间】:2014-07-21 12:37:11
【问题描述】:

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

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

它产生这个输出:

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

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

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;

更改 memcpy 以使用 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

这里到底发生了什么??

【问题讨论】:

  • 如果没有buffer 的声明及其与变量i2o2 等的关系,就无法判断。

标签: c++ char buffer sizeof memcpy


【解决方案1】:

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

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

【讨论】:

  • 我猜整个“参数(每个浮点数是 8 个字节)”评论让我失望:courses.washington.edu/css503/2014q2/assignment-4.html
  • 我猜他们的意思是双重的,而不是浮动的——记得接受
  • 是的,教练的意思可能是双重的……仍然浪费了很多时间。
  • @PatK 如果他们在学校教你这样的东西(无论是无名的小屋学院还是斯坦福大学),请立即离开那个地方。这是非常不专业、错误(在概念上和技术上)和有害的,特别是如果他们开始向初学者教授不良做法。
  • @PatK 链接文档中的示例是在谈论“浮点数”,而不是float,示例清楚地显示了用途double.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-02
  • 2017-04-02
  • 2012-05-27
相关资源
最近更新 更多