[英]Arduino is not freeing up RAM memory
I'm using Arduino mega with MD5 library and ESP8266 with SoftwareSerial. 我正在使用带有MD5库的Arduino mega和带有SoftwareSerial的ESP8266。 The problem is that after 370 loops, Arduino auto-restart due to lack of memory.
问题是370循环后,由于内存不足,Arduino自动重启。 I used FreeMemory to troubleshoot, I noticed the problem is the decreasing of available memory with each loop.
我使用FreeMemory进行故障排除,我注意到问题是每个循环的可用内存减少了。 It is weird behavior, because it only appears when I use AT commands along with MD5, however if I separate the sketch in two sketches they work properly without memory problems.
这是奇怪的行为,因为它只在我使用AT命令和MD5时出现,但是如果我在两个草图中分离草图它们正常工作而没有内存问题。 My original sketch is a quite more complex, but I reduced to the essential code the example showed bellow in order to be more clear, the behavior is the same, so if i fix it i will be able to fix the my original sketch
我的原始草图是一个相当复杂的,但我简化为实例所示的基本代码,以便更清楚,行为是相同的,所以如果我修复它,我将能够修复我的原始草图
#include <SoftwareSerial.h>
#include <MemoryFree.h>
#include <MD5.h>
void setup() {
// initialize the digital pin as an output.
Serial.begin(115200);
Serial.println("Starting");
Serial1.begin(115200);
delay(200);
}
// the loop routine runs over and over again forever:
void loop() {
Serial1.println("AT");
delay(100);
Serial.println(Serial1.readString());
Serial.println("-----------");
unsigned char* hash=MD5::make_hash("hello world, this an example");
//generate the digest (hex encoding) of our hash
char *md5str = MD5::make_digest(hash, 16);
//print it on our serial monitor
Serial.println(md5str);
//Give the Memory back to the System if you run the md5 Hash generation in a loop
free(md5str);
Serial.println(freeMemory());
}
Thanks! 谢谢!
Here is the source code of make_hash
: 这是
make_hash
的源代码:
unsigned char* MD5::make_hash(const void *arg)
{
MD5_CTX context;
unsigned char * hash = (unsigned char *) malloc(BLOCK_SIZE);
MD5Init(&context);
MD5Update(&context, arg, strlen((char*)arg));
MD5Final(hash, &context);
return hash;
}
As you can see, there is a malloc()
in there for the returned hash
variable. 如您所见,返回的
hash
变量中有一个malloc()
。 Therefore you should invoke free(hash)
at the end of each loop iteration. 因此,您应该在每次循环迭代结束时调用
free(hash)
。
If you need to keep hash
around, put it in the global scope and create it only once in the setup()
function. 如果需要保持
hash
,请将其放在全局范围内,并在setup()
函数中仅创建一次 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.