Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Storage binding a) Variables can be allocated in the stack, heap, or statically.

ID: 3796529 • Letter: S

Question

Storage binding

a) Variables can be allocated in the stack, heap, or statically. What accounts for these differences (e.g., performance)? Give an example C++ routine that would not work correctly if local variables are allocated statically.

I already know that an object will be allocated statically when that object is needed for entire life time of that program
If an object needs recursion and storage of object conserving then it is stored in stack
If object needs dynamic storage then it should be allocated in heap

What is the best c++ example routine that would not work correctly if local variables are allocated statically.

Explanation / Answer

Consider the following piece of code:

sum(f, low, high)

{

if (low = high)

return f(low)

else

return f(low) + sum(f, low + 1, high)

}

sum is a user defined funcion with variable low. The value of this variable has to be remembered during function call.