CSC 112
Lecture 13
Memory allocation using stacks
- Use of stacks for temporary memory allocation of parameters
and local variables of functions, during function calls.
- More applications of
stacks: memory allocation part I.
- How compilers treat global and local variables and function
parameters.
- How the call of a function is evaluated using a stack. How
the value returned by a function is stored on top of the system stack.
Preliminary reading for the next topic (how recursion is
implemented with stacks): textbook, Ch. 6.4, 8.6.2..
The rest of the class is devoted to working on Hw6.
Next
Recursion (whose implementation needs stacks)
- A recursive function is defined in such a way that it refers
to itself within its own definition.
- Simple example: a function int sum(int n)
to add all the numbers from 1 to
n. If n is 1, it returns the value 1. Otherwise, it adds n to the
sum of all the numbers from 1 to (n-1). Do you hear the
self-reference in this description?
Here is an implementation in
C++.
- How a recursive function call is evaluated. Trace the stack
during the function call for sum(4).
- More examples: a recursive function implementing a recursive
definition. A function testing whether a given arithmetic
expression
(given as a string of characters) is in
prefix form.
- When to use recursive functions? When you "hear" the
recursive reference in the very description of the function.
- Recursive algorithms: a very powerful technique of algorithm
design. Sometimes it produces very efficient algorithms.
- A few recursive definitions that you might "hear": the
factorial function (product of the the first n numbers); finding
the minimum element of an array; searching in an array; binary search.