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

2024-03-29

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

基本上,连接似乎有效,但在几次运行后会出现错误(不可读的字符、字符串变得更短而不是更长)或崩溃。它是可重现的,重启后在同一点崩溃。

我提取了几行 Arduino 代码来演示该问题。它执行以下操作:

  1. 创建一个随机数并将其写入数组(有效)
  2. AES-对该数组进行编码(有效)
  3. 构建每个数组索引的十六进制表示(有效)
  4. 将索引连接到字符串(崩溃)

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

我搜索了论坛,尝试了不同的方法来连接(+运算符,strcat)。所有这些都有类似的效果。我读到 String 库有一个 bug,将 Arduino IDE 更新到 1.0。

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

多谢!


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

检查你有多少内存free http://arduino.cc/playground/Code/AvailableMemory在你的循环期间。

罪魁祸首可能是 String 的实现(参见Arduino WString.cpp https://github.com/arduino/Arduino/blob/3dfc2c631110d912656d3bd02c7a07d16adcb6d3/hardware/arduino/cores/arduino/WString.cpp)正在使用 realloc(),并且您的内存可能会被一两个字节字符串(每个字符串都有 16 字节堆头成本)严重碎片整理。

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Arduino:连接字符串时崩溃和错误 的相关文章

随机推荐