Arduino:连接字符串时崩溃和错误

Kla*_* 71 6 string arduino string-concatenation

我尝试将AES-256加密的输出连接到一个字符串(将此字符串与从Android手机发送的加密字符串进行比较).

基本上,连接似乎有效,但经过几次运行错误(不可读的字符,字符串变短而不是更长)或崩溃发生.它是可重现的,在重启后在完全相同的点崩溃.

我提取了一些演示问题的Arduino代码.它执行以下操作:

  1. 创建一个随机数并将其写入数组(工作)
  2. AES-编码此阵列(工作)
  3. 构建每个数组索引的HEX表示(工作)
  4. 将索引连接到String(崩溃)

#include <SPI.h>
#include "aes256.h"  //include this lib

uint8_t key[] = {9,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8,
                 1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8 }; //the encryption key

aes256_context ctxt; //context needed for aes library


void setup() {  
  Serial.begin(9600);  
}


void loop() {

  uint8_t data[] = {
       0x53, 0x73, 0x64, 0x66, 0x61, 0x73, 0x64, 0x66,
       0x61, 0x73, 0x64, 0x66, 0x61, 0x73, 0x64, 0x65, }; //the message to be encoded  

  long InitialRandom = random(2147483647); //0 to highest possible long
  String RandomString = "" ; 
  RandomString+=InitialRandom; //random number to String            
  Serial.println(RandomString); //for debugging

  //update data array: Random String into data array                 
  for (int x=0; x<RandomString.length(); x++){
       data[x] = RandomString[x];
  }

  //this encrypts data array, which changes  
  aes256_init(&ctxt, key); //initialize the lib
  aes256_encrypt_ecb(&ctxt, data); //do the encryption     
  aes256_done(&ctxt);  

  //Here the problem starts.............................................
  String encrypted=""; //the string I need finally 

  for (int x=0; x<sizeof(data); x++){ //data array is 16 in size    
        int a = data[x]; 
        String b = String (a, HEX);
        if(b.length()==1) b="0"+b;  //if result is e.g "a" it should be "0a"                         
        encrypted.concat(b);  //this line causes the problem!!! 
        //Serial.println(b); //works perfect if above line commented out    
        Serial.println(encrypted); //see the string geting longer until problems occur      
  }
  //Here the problem ends.............................................

        Serial.println(); //go for next round, until crashing
}
Run Code Online (Sandbox Code Playgroud)

我搜索了论坛,尝试了不同的连接方式(+ operator,strcat).都有类似的效果.我读到String库有一个bug,将Arduino IDE更新为1.0.

这让我忙碌了好几天,非常感谢任何帮助,

非常感谢!

pet*_*ept 4

您可能会耗尽内存,因为 Arduino 只有少量内存。

检查循环期间有多少可用内存。

罪魁祸首可能是 String 的实现(请参阅Arduino WString.cpp)正在使用 realloc(),并且您的内存可能被一两个字节字符串(每个字符串都有 16 字节堆头成本)严重碎片整理。

您可以通过预分配 String Reserve() 函数来预分配缓冲区,从而更有效地重写上述内容。或者使用本机 C++ 字符数组重写它。