-->
Page 1 of 2

Heap or Stack??

PostPosted: Mon Dec 28, 2020 12:22 pm
by RichardS
Very knowledgeable about C when it involves heap and stack and variables, but in the CPP world it can be very different... still learning...

I would assume the answer is always stack... but is it?? does the Arduino String do anything heap-side?

void func() {
String s1; // heap or stack?
int x; // i know this is stack

String s2 = s1 + "temp"; // s2 heap or stack, intermeadiate "temp" heap or stack?
int x1 = x + 2; // i know this is still all stack

// if these strings are on the heap, are they removed when the function exits?
}

RichardS

Re: Heap or Stack??

PostPosted: Mon Dec 28, 2020 2:46 pm
by quackmore
other than stack and heap you will find at least the following:

text (code)
data (initialized variables read and write)
rodata (constants, like data but read only)
bss (not initialized variables)

so:

Code: Select allvoid func() {
String s1;     // s1 (the String object) is allocated on stack
                    // some methods inside s1 (String implementation) may allocate heap memory
                    // some attribute inside s1 (String implementation) may point to heap memory

int x; // i know this is stack,     ->     ya, it is

String s2 = s1 + "temp"; // s2, same as above
                                      // "temp" is a constant, that's rodata

int x1 = x + 2; // i know this is still all stack
                      // nope, same as above: x1 and x are on stack, '2' is rodata

// if these strings are on the heap, are they removed when the function exits?
// s1 and s2 are local variables, they don't exist outside the function scope, when the function ends the String destructor is invoked and it will free any heap allocated memory
}

Re: Heap or Stack??

PostPosted: Mon Dec 28, 2020 3:40 pm
by RichardS
This is exactly as I expected, I was actually not referring to the constants being on stack... that would be nuts :-)

Another question, what happens when you return a class in a function?

String name() {
String s = "rick";

return s;
}

String class is on the stack, "rick" is most likely in heap, or at least if the string was really long, as I think short strings are actually on stack in the Arduino String class... (until they grow too large)

Let assume it in the heap.... so when the function returns s deconstructor should be called, which normally frees the heap, so where is this String that was returned?, and when does its deconstuctor get called to release its heap??

This would apply to many Classes, I am just using String as an example, to make ESP8266/ESP32 happier....

RichardS

Re: Heap or Stack??

PostPosted: Mon Dec 28, 2020 5:02 pm
by quackmore
Returning a class by value will invoke a 'copy constructor'

the 'return' instruction will copy the local variable to an external (to the function) one

Then the local variable destructor will be invoked

It is safe to assume that the heap content will be duplicated too