0

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)?

2 Answers 2

2

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"));
Sign up to request clarification or add additional context in comments.

2 Comments

So since it's a macro i can just add the F() and it will just work? There are several functions suffixed with _P to work with program memory. Will this work with the LiquidCrystal Library without any trouble?
If you use the Arduino IDE, I think this should work with any strings you are using. Just try it out.
1

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:

  1. 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.

  2. 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.

  3. The amount of memory used by those variables is not accounted for in the calculation of "used" RAM at compile time.

1 Comment

Thank you for a very detailed and informative answer. It answered my question in more detail than I expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.