Arduino:字符串连接困难

Arduino: Difficulty with String concatenation

本文关键字:连接 字符串 Arduino      更新时间:2023-10-16

我(错)使用Arduino字符串类。我的整个程序:

void setup() { 
  Serial.begin(9600);
}
void loop() { 
  const String args[3] = {
    "foo", "bar", "baz"    };
  String result = "";
  Serial.println(result);
  result += args[0];
  Serial.println(result);
  result += args[1];
  Serial.println(result);
  result += args[2];
  Serial.println(result);
  Serial.println();
}
这个打印

:

foo
foobar
foobarbaz

foo
foobar
foobarbaz

foo
foobar
foobarüÿ

foo
foobar
foobarüÿ

foo
foobar
foobar

foo
foobar
foobarüÿ

foo
foobar
foobarüÿ

foo
foobar
foobarüÿ

我不知道为什么它不总是打印:

foo
foobar
foobarbaz

我做错了什么?

Update:我尝试添加第四个字符串到数组。现在程序在通过loop()大约15次后停止运行。

更新2:以下是String附加操作符的代码:

const String & String::operator+=( const String &other )
{
  _length += other._length;
  if ( _length > _capacity )
  {
    char *temp = (char *)realloc(_buffer, _length + 1);
    if ( temp != NULL ) {
      _buffer = temp;
      _capacity = _length;
    } else {
      _length -= other._length;
      return *this;
    }
  }
  strcat( _buffer, other._buffer );
  return *this;
}

更新3:如果我替换:

  String result = "";

:

  String result = args[0];

问题消失了。有趣。

奇数字符是堆内存损坏的结果。

你的代码没有问题。这是当前Arduino软件使用的内存分配例程版本存在缺陷的表现。它目前与AVR Libc 1.6.4一起发布,其中包含许多在最新的1.7.1版本中修复的内存分配问题。

我使用对Arduino软件的teensyduino增强在teensyduino 2.0板上成功运行了此代码(即没有显示奇数字符)。这包含了对这些内存问题的修复,但不幸的是,这些修复不适用于编程Arduinos。

有计划在2011年8月将官方Arduino软件升级到最新的AVR Libc。

这看起来像是内存被覆盖的典型症状。您必须查看程序的其他部分才能找到罪魁祸首,因为您在这里显示的任何内容都不会导致此问题。

除此之外,您发布的手册页不建议String支持+=操作符。