Questions related to ESP stack and Heap
Posted: Thu May 14, 2020 8:48 pm
Hello everyone! I'm having some issues related to the ESP stack and heap understanding, and I'd like some help.
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:
The output was the following:
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?
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:
Code: Select all
#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:
Code: Select all
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?