Stack and Dynamic Local Variables in Subprograms
Stack and Dynamic Local Variables in Subprograms
● Local Variables:
Variables that are declared inside a subprogram and are only
accessible within that subprogram.
○ These are created on the stack when the subprogram is called and
destroyed when the subprogram finishes.
○ Scope: The scope of these variables is local to the subprogram (i.e.,
they can only be accessed within the function they are declared).
○ Lifetime: The lifetime of these variables is limited to the execution of
the subprogram call. Once the subprogram returns, these variables are
destroyed.
● Stack Frame (Activation Record): The stack frame created for a
subprogram call holds:
x=5
y = 10
z = multiply(x, y)
While most local variables are created on the stack, dynamic local variables are
used when:
● The size of the variable is not known ahead of time (e.g., creating a dynamic
array or list).
● The variable's lifetime needs to extend beyond the scope of a single function
call (though this is typically handled through dynamic memory allocation
and explicit deallocation).
● The variable's memory should not be tied to the function's execution context
(e.g., it needs to persist even after the function exits).
1. Memory Allocation:
○ Stack Variables: Stack variables are only visible within the scope of
the subprogram in which they are declared.
○ Dynamic Variables: Dynamic variables can be visible across
different functions or even threads if they are passed around explicitly.
Their scope can be controlled through pointers or references.
Example of Dynamic Memory Allocation (C/C++)
In C or C++, dynamic memory is often used to allocate local variables like arrays
where the size isn't known at compile time. For example:
#include <stdio.h>
#include <stdlib.h>
int main() {
create_array(5); // Create an array of size 5
return 0;
}
Breakdown:
1. Variable Size Arrays: When you need to create an array where the size isn't
known at compile time.
2. Memory Management: For efficient memory management when the
number of elements required is large or unpredictable, and you want to avoid
the limitations of stack memory size.
3. Recursion with Variable Memory: In recursive functions, dynamic
memory allocation can be used for storing structures or arrays whose size
varies with recursion depth.
4. Data Structures: Dynamic variables are essential for implementing
complex data structures like linked lists, trees, or graphs, where elements are
created and destroyed dynamically during program execution.
● Stack Overflow: If the function calls are deeply nested or use too many
local variables, especially in recursive functions, you can run out of stack
space, causing a stack overflow.
○ In Java, local variables are stored on the stack, but objects (e.g.,
arrays, classes) are allocated on the heap. Java uses automatic garbage
collection to manage dynamic memory.
●
○ In Java, the array arr is allocated on the heap, and the stack holds the
reference to it.