How to track a recursive function's call stack usage
<p>I am teaching a class to intro C++ students and I want to design a lab that shows how recursive functions differ from iteration. My idea was to track the memory/call stack usage for both and display the difference. I was almost positive that I had done something similar when I did my degree, but can't remember. My experience doesn't lie in C/C++ so any guidance would be appreciated.</p>
<h1>Update 1:</h1>
<p>I believe I may have miss represented my task. I had hoped to find a way to show how recursion increases the overhead/stack compared to iteration. I followed some suggested links and came up with the following script.</p>
<pre><code>loops=100
counter=0
total1=0
echo &quot;Iteration&quot;
while [ $counter -lt $loops ]; do
    &quot;$1&quot; &amp; # Run the given command line in the background.
    pid=$! peak1=0
    echo -e &quot;$counter.\c&quot;
    while true; do
    #sleep 0.1
        sample=&quot;$(pmap $pid | tail -n1 | sed 's/[^0-9]*//g' 2&gt; /dev/null)&quot; || break

        if [ -z &quot;$sample&quot; ]; then
            break
        fi
        let peak1='sample &gt; peak1 ? sample : peak1'
    done
#    echo &quot;Peak: $peak1&quot; 1&gt;&amp;2
    total1=$(expr $total1 + $peak1)
    counter=$[$counter+1]
done
</code></pre>
<p>The program implements a binary search with either iteration or recursion. The idea is to get the average memory use and compare it to the Recursion version of the same program. This does not work as the iteration version often has a larger memory average than the recursion, which doesn't show to my students that recursion has drawbacks. Therefore I am pretty sure I am doing something incorrect.</p>
<p>Is pmap not going to provide me with what I want?</p>