-->
Page 1 of 1

Questions related to ESP stack and Heap

PostPosted: Thu May 14, 2020 8:48 pm
by Lucas Reis
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:
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 allFree 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?

Re: Questions related to ESP stack and Heap

PostPosted: Sat May 16, 2020 12:32 pm
by Pablo2048
Hi,
I think that the problem is in explanation of getFreeContStack. AFAIK it is not the actual free stack size, but highest (or lowest) watermark - see https://github.com/esp8266/Arduino/issues/5148 .

Re: Questions related to ESP stack and Heap

PostPosted: Sat May 16, 2020 5:21 pm
by Lucas Reis
Oh yes it is! Thank you so much, that makes sense now :D