Reputation: 130
I'm using Arduino mega with MD5 library and ESP8266 with SoftwareSerial. The problem is that after 370 loops, Arduino auto-restart due to lack of memory. I used FreeMemory to troubleshoot, I noticed the problem is the decreasing of available memory with each loop. 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. 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!
Upvotes: 3
Views: 1413
Reputation: 7342
Here is the source code of 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. Therefore you should invoke free(hash)
at the end of each loop iteration.
If you need to keep hash
around, put it in the global scope and create it only once in the setup()
function.
Upvotes: 4