Answers/Solutions to Exercises in Chapter 8, Exercise 8
E8: \What will happen in the following C++ program if the display statement in main() is uncommented and the program is recompiled and executed? Can you describe the output?
class A { public: char* heap_string; char* stack_string; A() { heap_string = stack_string = 0; } void AttHStr(char* x) { heap_string = x; } void AttSStr(char* x) { stack_string = x; } friend ostream& operator<< (ostream& os,const A& a) { os << "heap string=\"" << a.heap_string << "\"\n"; os << "stack string=\"" << a.stack_string << "\"\n"; return os; } }; A a; void doit() { char s[] = "..stack.."; a.AttSStr(s); cout << a << '\n'; } int main() { a.AttHStr(strdup("..heap..")); doit(); // cout << a << '\n'; return 0; }
A8: The global object a is created by compiler. The first statement of main() sets the a.heap_string to point to a the string "..heap.." that is on the system heap. Then comes the call to doit()that sets the a.stack_string to point to the string "..stack.." that is on the system stack, and the object a is displayed providing two messages on the screen
heap string="..heap.." stack string="..stack.."
When back in main(), the a.stack_string is in fact a dangling pointer. Thus the call to cout may produce any kind of garbage or even crash the program:
heap string="..heap.." stack string="Ç ?"
Back to Answers/Solutions Index Back to Answers/Solutions for Chapter 8 Index