2011-04-25 75 views
2

我是(mis-)使用Arduino String類。我的整個程序: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 

什麼可能我是做錯了什麼?

更新:我試着向數組中添加第四個字符串。現在程序通過loop()左右15次停止運行。

更新2:這裏是codeString追加操作:

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

問題消失。有趣。

+0

嗯,爲什麼不使用std :: string? – 2011-04-26 00:28:52

+1

這是在Arduino上可用嗎?我不認爲這是。 – 2011-04-26 01:51:59

+0

arduino有一個STL端口:http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1295132807,但是,就像作者說的那樣,你需要仔細觀察你的記憶。 – dusktreader 2011-06-01 23:32:41

回答

1

這看起來像是內存被覆蓋的典型症狀。你必須在程序的另一部分尋找罪魁禍首,因爲你在這裏展示的東西都不會造成這種情況。

+1

已更新,以包含我的整個程序。它沒有任何我懷疑是罪魁禍首的東西。 – 2011-04-25 23:58:18

0

除此之外,您發佈的手冊頁不會建議String支持+ =運算符。可能發生了一些不必要的轉換,這樣可以調用這樣的操作員。

+2

「operator +」的文檔顯示爲「+ =」作爲可接受的語法。不是記錄它的最佳方式,但是... – 2011-04-25 21:01:19

+0

@Mark Argh!這太可怕了!圖形設計超越功能的典型例子。 – 2011-04-25 21:03:56

4

奇怪的字符是堆內存損壞的結果。

您的代碼沒有任何問題。這是當前Arduino軟件所使用的內存分配例程版本中缺陷的一種表現形式。它目前附帶AVR Libc 1.6.4,其中包含許多在最新的1.7.1版本中修復的內存分配問題。

我使用teensyduino對Arduino軟件的增強功能成功運行了該代碼(即,不顯示奇數字符)Teensy 2.0 board。這包含了這些內存問題的修復,但不幸的是這些修復在編程Arduinos時不適用。

有計劃在2011年8月將官方Arduino軟件升級到最新的AVR Libc。