Reputation: 1744
If I declare an array in the global scope, it uses up memory to store it. However, if I declare an array (I am using two types, one is a char array, while the other is an int array) inside a function (such as setup()
) will the memory be freed automatically once the array goes out of scope?
I believe this happens for some variables such as int or byte. I just wanted to know if this applies to arrays as well.
Also, since I read that for programs containing lots of strings, it is best to store them in program space, does a call such as
lcd.print("Hello")
still use up the memory for the "Hello" string after the function ends (assuming that the print function does not store it someplace else)?
Upvotes: 0
Views: 2020
Reputation: 1915
To the second question:
The F()
macro will store strings in the progmen instead of using RAM, so you do not have this problem anymore:
lcd.print(F("Hello"));
Upvotes: 2
Reputation: 12610
As to your 1st question: Yes. All variables declared inside a function are only valid inside until the function returns and are released automatically then. This has some implications:
You must not use a pointer to a locally declared variable after the variable went out of scope, for instance, after the function returned. (Don't return a pointer to a local array from your function!) - It is however perfecly legal to pass that pointer to other functions when calling them from within the declaring block/function.
Local variables are stored on the local stack so that there needs to be enough room left for the stack to grow by the corresponding number of bytes when the function is called.
Upvotes: 1