(C++ concept on local variable) On page 14 of the “Pointers and Memory” handout
ID: 3796207 • Letter: #
Question
(C++ concept on local variable) On page 14 of the “Pointers and Memory” handout there is a reference to the “Amperand (&)” Bug in the TAB() function. Draw a trace of the local variables of the functions Victim() and TAB() on the run-time stack as these functions are executed. Your diagram should be similar to the one provided on page 13. Your diagram should depict exactly three instances in program execution - T1: Right after the first statement of Victim(), T2: right before the return statement in TAB(), T3: Right after the call to TAB(). Use your diagram to explain the “Amperand (&)” bug and why it is likely to lead to a runtime error when the last line of the Victim() is executed?
This is the code on page 14
// TAB -- The Ampersand Bug function
// Returns a pointer to an int
int* TAB() {
int temp;
return(&temp); // return a pointer to the local int
}
void Victim() {
int* ptr;
ptr = TAB();
*ptr = 42; // Runtime error! The pointee was local to TAB
Diagram on page 14
Explanation / Answer
Note that, the problem with this code is that, in TAB(), the function has a local stack variable, and once the scope of that variable temp, is only within the function TAB(). Once, out of the funciton, the stack for TAB() will be deallocated, and temp is no more available, and the memory to which temp is pointing to is also not available. But you're returning the address of temp which the method Victim() don't have access to.
This leads to a dangling pointer kind of problem. In simple terms, you're pointing to somewhere where you don't have access to, or infact, to a location which doesn't exist within your limits.
T1 - Right after the first statement of Victim(), ptr is an integer pointer just declared, and not initialized. T2 - Right before the return statement in TAB(). A local variable temp is declared, and not initialized. T3 - Right after the called to TAB(). Here ptr is assigned with an address which is not in the stack, or heap. Victim(): ptr Tab(): temp Victim(): ptrRelated Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.