In: Computer Science
could you explain stack frame and local variables saved on stack.
also explain recursive programs -- what is stack over flow? What is a stopping case for recursive codes?
A stack frame sometimes also referred to as an activation record is the collection of all the data on the stack associated with one subprogram call.
In simple terms whenever we double-click on any program in our system to run it, it gets loaded into the main memory for execution. Now the program is loaded as a stack into the memory with various subparts, where each subpart contains specific things for some specific purposes. Each part in some way helps in the execution of the program. Some of the parts of a stack frame can include:- The return address, Local variables, program registers, and so on.
Local variables are the variables that have a local scope which means that they are defined inside the functions. These are the variables in High-level language that are not declared as static. These actually reside in the stack frame and have an automatic storage class. When the program enters a block such as a function or a method, space is allocated on top of the stack for the local variables.
Recursive programs:- We know that a program can also include functions. A function is a reusable piece of code that can be used again by simply calling the name of the function. A recursive program is a program that contains a special kind of such function called as a recursive function. A recursive function is one that calls itself in its function definition.
A recursive function must have two parts:-
a) A general case, i.e., the case for which the solution is given in terms of a smaller version of the current problem.
b) A base case, where the program comes and stop making further calls to itself. This is the stopping case for a recursive program. Without this, a recursive program will keep calling itself and until the program or the system itself crashes.
Stack Overflow:- It is a condition when a function or program uses more memory than is in the stack. As it grows beyond its allocated space, the dynamic stack contents begin to overwrite other things, such as critical application code and data. A stack overflow condition will lead the program to crash. There are two conditions which can lead to stack overflow:-
a) First the most obvious is if we declare a very large no. of local variables or declare an array or matrix or any higher dimensional array of large size can result in overflow of the stack.
b) If a function recursively calls itself infinite times then the stack is unable to store large no.of local variables used by every function call and will result in overflow of the stack. This will happen when our recursive function does not have a termination condition.
Hope this helps. If you have any queries or suggestions regarding the answers please leave them in the comments section so I can update and improve the answer. Thank you.