c++ - 奇怪的 C++ Arduino 串行行为

标签 c++ arrays arduino

我正在为我的 arduino 编写一些代码以从模拟操纵杆打印 4 个按钮状态和 X、Y 坐标,但我有奇怪的行为。

代码如下:

  int x,y;
  x = analogRead(joy_x);
  y = analogRead(joy_y);
  char* buf = new char[4];
  sprintf(buf, "%4d", x);
  Serial.print("X:");
  Serial.print(buf);
  Serial.print(" Y:");
  sprintf(buf, "%4d", y);
  Serial.println(buf);

  int one,two,three,four;
  one = digitalRead(touchOne);
  two = digitalRead(touchTwo);
  three = digitalRead(touchThree);
  four = digitalRead(touchFour);

  // create an array of states set to the default values
  char states[4] = {'X', 'X', 'X', 'X'};
  // change each value if it is not in the default state
  if(one   == 1) states[0] = 'O';
  if(two   == 1) states[1] = 'O';
  if(three == 1) states[2] = 'O';
  if(four  == 1) states[3] = 'O';
  // output the states to the OLED display
  //display.print(states);
  Serial.print(states);

当它运行时,串行输出如下所示:

XXXX3X: 515 Y: 520
XXXX3X: 516 Y: 520
XXXX3X: 516 Y: 519
XXXX3X: 516 Y: 520
XXXX3X: 515 Y: 520
XXXX3X: 516 Y: 519
XXXX3X: 516 Y: 520
XXXX3X: 515 Y: 519
XXXX3X: 516 Y: 520

尽管 X、Y 应该在 XXXX 之前并且数字 3 不知从何而来。 希望能解开这个谜团,谢谢。

最佳答案

您的代码中有几个缓冲区溢出。

  char* buf = new char[4];
  sprintf(buf, "%4d", x);
  ...
  sprintf(buf, "%4d", y);

这需要为 sprintf 添加的空终止符留出空间。

  char* buf = new char[5];

也更容易:无需使用此处的免费商店。

  char buf[5];

同样的事情在这里:

  char states[4] = {'X', 'X', 'X', 'X'};
  ...
  Serial.print(states);

我们需要添加一个空终止符以使其成为一个有效的字符串。

  char states[5] = {'X', 'X', 'X', 'X', '\0'};

这应该可以解决即时内存问题。

关于c++ - 奇怪的 C++ Arduino 串行行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33856248/

相关文章:

php - 如果数组是使用 explode() 创建的,in_array() 将不再像预期的那样工作

python - 在循环中的 Python 中 append 矩阵

c - Arduino 中的代码相同但输出不同

c++ - 在 Arduino 中使用虚拟方法

c++ - 是否不可能将对 const 指针的引用返回到 const 数据?

c++ - 由于换行字符不同的结果

c++ - 结构中包含数组的结构数组

c++ - C++ 中的原子性 : Myth or Reality

javascript - 使用额外的方法和语法糖扩展 Javascript 数组

java - 丢弃数字的前 10 位