Your new topic does not fit any of the above??? Check first. Then post here. Thanks.

Moderator: igrr

User avatar
By RichardS
#89983 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
User avatar
By quackmore
#89985 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
}
User avatar
By RichardS
#89986 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
User avatar
By quackmore
#89990 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