question about memory usage of a program at runtime

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?

Thanks!
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.

Read about the "call stack", and in particular the "stack frame"; http://en.wikipedia.org/wiki/Call_stack#The_stack_and_frame_pointers
Last edited on
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?
Last edited on
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.
yeah but if you declare a variable in a for or an if, is the variable destroyed and the memory freed after the for/if (or while) is executed ?
Last edited on
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.
ok thanks a lot!
Topic archived. No new replies allowed.