开发者

Arduino: Difficulty with String concatenation

I'm (mis-)using the Arduino String class. My entire program:

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();
}

This prints:

foo
foobar
foobarbaz


foo
foobar
foobarbaz


foo
foobar
foobarüÿ


foo
foobar
foobarüÿ


foo
foobar
foobar


foo
foobar
foobarüÿ


foo
foobar
foobarüÿ


foo
foobar
foobarüÿ

I'm not sure why it doesn't just always print:

开发者_StackOverflow中文版
foo
foobar
foobarbaz

What could I be doing wrong?

Update: I tried adding a fourth string to the array. Now the program stops running after 15 times through loop() or so.

Update 2: Here is the code for the String append operator:

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;
}

Update 3: If I replace:

  String result = "";

with:

  String result = args[0];

The problem goes away. Interesting.


The odd characters are a result of heap memory corruption.

There is nothing wrong with your code. This is a manifestation of a defect in the version of the memory allocation routines used by the current Arduino software. It currently ships with AVR Libc 1.6.4 which contains a number of memory allocation issues fixed in the latest 1.7.1 release.

I have run this code successfully (i.e. without the odd characters being displayed) on a Teensy 2.0 board using the teensyduino enhancement to the Arduino software. This contains fixes for these memory issues but unfortunately these fixes don't apply when programming Arduinos.

There are plans to upgrade the official Arduino software to the latest AVR Libc in August 2011.


This looks like a typical symptom of memory being overwritten. You'll have to look in another part of the program to find the culprit, because nothing you show here would cause this.


Apart from anything else, the manual page you posted does not suggest that String supports += operator. Possibly some unwanted conversion is going on that allows such an operator to be called.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜