C/C++ Memory Problem?
-
10-07-2019 - |
Question
Programming for my Arduino (in some kind of mix of C/C++), I noticed something weird.
Everytime I communicate through the serial port, I keep an eye on the SRAM usage. Normally, it ranges between 300~400 bytes. However, after adding a new routine (see below), I noticed it always jumped from 300~400 bytes of free memory to EXACTLY 1023. My hunch is that there's a problem.
This is the new routine
void NewRoutine(char *cmdd){
GSM.print(cmdd);
GSM.print(26, BYTE);
GSM.print(endl); // <-- added later
Serial.print(availableMemory());
}
And this is the MemoryCheck Routine
int availableMemory() {
int size = 1024;
byte *buf;
while ((buf = (byte *) malloc(--size)) == NULL);
free(buf);
return size;
}
Please note this: First, it didn't work. After I added the endl command, it worked magically, but then I noticed the memory issue.
Anyone got ideas for a workaround?
Solution
The reason you're getting 1023 bytes of free memory is purely because the malloc (on 1023 - which is --1024) is succeeding on the first try. This means you have at least 1023 bytes of memory - but doesn't tell you the true available memory.
Prior to this, you must have had something keeping memory around. My guess is the GSM class here - it probably holds the data (cmdd + 26) in an internal buffer which is flushed on a newline. As soon as you added your endl call, you're probably getting the full memory back from the buffer.
How large is your command? My guess is that it (or the full set of them) is probably around 700 bytes...
OTHER TIPS
Maybe it holds a buffer on the heap to transfer data to the serial port?