DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
No More Memory Leaks - fs(3C++)

Program #2: Setting a watchpoint

Consider the following program:

     prog2.c:
      class X {
          int x;
      } *x;
      void f() { /*...*/ }
      void g() { /*...*/ }
      void h() { /*...*/ }
      void i() { /*...*/ delete x; }
      void j() { /*...*/ }
      main() {
          x = new X;  // line 1
          f();
          g();
          h();
          i();
          j();
      }

Suppose we wish to print out the value of the object newed on line 1 just before it is deleted. Unfortunately, there is in general no easy way to tell, by examining the source code of a program, where a given object is deleted. The call to delete which deletes the object can be far removed in time and space from the call to new which newed it. Furthermore, the argument to delete can be an arbitrarily complex expression which may bear no syntactic relationship to the original variable into which the pointer to the object was first placed (x in the above program). fs to the rescue.

For the sake of illustration, suppose we are already in the process of debugging this program:

Notice that the first thing we did after loading the program into the debugger was to set a breakpoint on the function fs_break(). As discussed in the section, ``fs to the Rescue'', fs_break() is an empty function, called whenever fs ``requests'' a break. Setting a breakpoint on fs_break() enables these requests to be fulfilled.

At this point, we wish to print out the value of the object newed on line 1 just before it is deleted. First we check to see whether it has already been deleted (if it has, then we'll have to restart the program from the beginning).

Luckily, the object still exists. We set a watchpoint on it.

And now, when we continue execution, eventually the program breaks with an announcement that our object is about to be deleted.

Voila!


Next topic: The Implementation
Previous topic: Program #1: A memory leak

© 2004 The SCO Group, Inc. All rights reserved.
UnixWare 7 Release 7.1.4 - 27 April 2004