according to the official documentation of the Arduino, the SRAM memory (which is allocated for the local variables) should be automatically released after calling any function. For example, I have a function memory_allocate_test2
, which declares a large char array and this function is called in the loop(). I expect, that every time, after the function memory_allocate_test2
is executed, the SRAM memory that I allocated for the local variables within that function should be freed or released. However, it is not working like that. When I call that function in a loop() the microcontroller hangs and stops working because it runs out of the available SRAM memory. Let me provide an example code:
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only - development mode. It has to be removed when releasing to live!!!
}
}
void loop() {
delay(2000);
memory_allocate_test2();
}
void memory_allocate_test2() {
Serial.println("memory_allocate_test2 STARTING ");
display_freeram();
Serial.println("------------------------------------------------------------");
Serial.println("Allocating the memory for the MKR: ");
char* memory_usage_test = new char[2000];
Serial.println("Allocated memory!");
display_freeram();
Serial.println("------------------------------------------------------------");
}
extern "C" char* sbrk(int incr);
void display_freeram(){
Serial.print(F("- SRAM left: "));
Serial.println(freeRam());
}
int freeRam() {
char top;
return &top - reinterpret_cast<char*>(sbrk(0));
}
why it doesn't work as it states in the documentation? what I'm doing wrong? why the SRAM memory is not released each time after the memory_allocate_test2
function execution?
https://www.seeedstudio.com/blog/2021/04/26/managing-arduino-memory-flash-sram-eeprom/
when I execute that program, here is what happens:
memory_allocate_test2 STARTING
- SRAM left: 7163
Allocating the memory for the MKR: Allocated memory!
- SRAM left: 5155
memory_allocate_test2 STARTING
- SRAM left: 5155
Allocating the memory for the MKR: Allocated memory!
- SRAM left: 3147
memory_allocate_test2 STARTING
- SRAM left: 3147
Allocating the memory for the MKR: Allocated memory!
- SRAM left: 1139
memory_allocate_test2 STARTING
- SRAM left: 1139
Allocating the memory for the MKR: Allocated memory!
- SRAM left: -869
memory_allocate_test2 STARTING
- SRAM left: -869
Allocating the memory for the MKR:
at that point the device just hangs and stops working. That's not what I expect!
since the functionality differs for each board and microcontroller, here are my specs: the board name is "Arduino® MKR WiFi 1010", the microcontroller name is "SAMD21 Cortex®-M0+ 32bit low power ARM MCU"