So basically, if I understand it right, in most cases local variables are stored on the stack, and global and static variables are stored on the heap.
To test this, I wrote the following code:
#include <Arduino.h>
void debugMemory()
{
Serial.printf("Free stack: %u\n", ESP.getFreeContStack());
Serial.printf("Free heap: %u\n", ESP.getFreeHeap());
}
void diagnose()
{
Serial.printf("Entering diagnose\n\n");
debugMemory();
Serial.printf("\nCreating 1000 char on stack\n");
debugMemory();
char hey[1000] = "Hello";
memset(hey, 0, 999);
Serial.printf("Var created\n");
debugMemory();
Serial.printf("\nCreating 1000 char on heap\n");
debugMemory();
char *heyTwo = new char[1000];
Serial.printf("Var created\n");
debugMemory();
Serial.printf("\nFreeing heap\n");
delete[] heyTwo;
debugMemory();
Serial.printf("Finished diagnose\n\n");
}
void setup()
{
// put your setup code here, to run once:
Serial.begin(115200);
while (!Serial)
{
};
debugMemory();
diagnose();
debugMemory();
Serial.printf("Finished!\n");
}
void loop()
{
// put your main code here, to run repeatedly:~
debugMemory();
while (1)
{
delay(1000);
}
}
The output was the following:
Free stack: 3872
Free heap: 51552
Entering diagnose
Free stack: 2476
Free heap: 51552
Creating 1000 char on stack
Free stack: 2256
Free heap: 51552
Var created
Free stack: 2256
Free heap: 51552
Creating 1000 char on heap
Free stack: 2256
Free heap: 51552
Var created
Free stack: 2256
Free heap: 50544
Freeing heap
Free stack: 2256
Free heap: 51552
Finished diagnose
Free stack: 2256
Free heap: 51552
Finished!
Free stack: 2256
Free heap: 51552
Observing the heap allocation, everything worked just fine. However I can't understand why the stack stayed at 2256 even after the diagnose function ended. Shouldn't the local variables be freed from memory after the function execution ended? If not, how can I free the stack?