HI! I have a question about the way a program handles memory during runtime. If I call a function in which I've declared a variable, the system allocates memory to hold that variable's data, but when the function has finished executing, is the memory space used by that function freed? In other words, is it more memory efficient to use dynamic memory in function declarations instead of regular variables?
In other words, is it more memory efficient to use dynamic memory in function declarations instead of regular variables?
No. It is much, much less memory efficient.
when the function has finished executing, is the memory space used by that function freed?
Yes. When a function finishes, everything local to that function is destroyed and the memory made completely available for the next function. If you use dynamic memory, the memory remains in use until you explicitly clear it up.
thanks a lot! I presume it's the same for ifs, for and whiles? Does it work the same for anything that has braces, and are braces the only provider of scope?
The stack frame is handed out for the function as a whole; additional stack frames are not handed out for if, while, braces, or other things inside a function.
Braces are a provider of scope; other scopes exist, such as the global scope and the namespace scopes.
The variable is destroyed (i.e. its destructor is called). The memory that was set aside for it is part of the stack frame and that memory gets returned for other use when the function ends.