    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Debug new and delete Part 3</title>
        <link>https://members.accu.org/index.php/journals/569</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>


        <h2>Journal Articles</h2>


<div class="xar-mod-head"><span class="xar-mod-title">Overload Journal #29 - Dec 1998 + Programming Topics</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c78/">Overload</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c199/">29</a>
                    (12)
<br />

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c65/">Programming</a>
                    (877)
<br />

                                            <a href="https://members.accu.org/index.php/journals/c199-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c199+65/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Debug new and delete Part 3</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 27 December 1999 17:23:23 +00:00 or Mon, 27 December 1999 17:23:23 +00:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<div class="section" lang="en">
<div class="titlepage">
<h2><a name="d0e18" id="d0e18"></a></h2>
</div>
<p>Experienced C and C++ developers are aware of the problem of
allocating free store, at run-time, which is not deallocated by the
time the program terminates. The problem is known as memory
leakage. In order to detect the fifth case [see Overload 23 &amp;
24] where memory is leaked by a program, there obviously has to be
method of recording all calls to the global scope <tt class=
"function">::new</tt> and <tt class="function">::delete</tt>
operators.</p>
<p>A practical solution for any record keeping project is to choose
an appropriate data structures for the element record and a
container to maintain the records. We can use classes in C++. We
can place the behaviours that directly deal with elements in the
record class and the behaviours that directly deal with containers
in the record container class. This is a very basic <span class=
"emphasis"><em>object based</em></span> idiom. There is no need for
inheritance (<span class="emphasis"><em>object
orientation</em></span>) here.</p>
<p>I have chosen to implement a container for dynamic memory
tracking [<a href="#Pilgrim">Pilgrim</a>] that is deliberately
simple and propriety. No Standard Template Library constructs are
used, because the container must be available immediately at
run-time without any other complicated dependencies. In particular,
the container is statically declared, in the global scope
namespace. Remember C++ constructs global objects (like the
standard I/O objects <tt class="classname">cout</tt>, <tt class=
"classname">cin</tt>, and <tt class="classname">cerr</tt>) before
the <tt class="function">main()</tt> program is called. (Yes I know
that I should be using a private library namespace, but for the
sake of this article I want to keep things simpler for the novice
reader at least.)</p>
<p>But, before I describe the data record and container. The
problem of conditionally compiling debugging (and linking) the
eventual debuggable new and delete library remains to be
solved.</p>
<p>It took quite a while for me to work out a reasonable compromise
between the C++ preprocessor's terseness and having acceptable and
readable macro definitions. I decided to intercept the allocation
and deallocation of dynamic memory with two global scope namespace
functions called _<tt class="function">register_memory()</tt> and
_<tt class="function">unregister_memory()</tt>. Here are the
macros:</p>
<pre class="programlisting">
#ifdef DEBUG_NEW
#define DBG_NEW(type,params) \
  (type*)_register_memory( 
       new type params , __FILE__, __LINE__ )
#define DBG_NEW_ARRAY(type,nelems) \
  (type*)_register_memory( 
       new type[nelems], __FILE__, __LINE__ )
</pre>
<pre class="programlisting">
#define DBG_DELETE(ptr) \
  delete (_unregister_memory( (ptr), 
                         __FILE__, __LINE__ ))
#define DBG_DELETE_ARRAY(ptr) \
  delete [] (_unregister_memory( (ptr), 
                         __FILE__, __LINE__ ))
#endif /*DEBUG_NEW*/
</pre>
<p>Notice that we pass the actual filename and the line number to
the registration functions. This is information is essential to
tracking later memory leaks.</p>
<p>Consider the usual way of writing these calls:</p>
<pre class="programlisting">
class X { 
    X() { ... }      // default constructor
    X( int aa, int bb, int cc ) { ... }
    ...
};

void f() {
  X *px = new X(1,2,3);
  X *pax = new X[100];
  delete px;
  delete [] pax;
}
</pre>
<p>Using the debuggable new and delete macros the code changes, in
particular the constructor, only slightly. The idea is to avoid
disturbing the casual reader with wild unfamiliar macros:</p>
<pre class="programlisting">
void f(){
  X *px = DBG_NEW( X, (1,2,3) );
  X *pax = DBG_NEW_ARRAY( X, 100 );
  DBG_DELETE(px);
  DBG_DELETE_ARRAY(pax);
}
</pre>
<p>Similarly when we need to switch off the debuggable new macros
for production code the definitions become:</p>
<pre class="programlisting">
#ifndef DEBUG_NEW
#define DBG_NEW(type,params) new type params
#define DBG_NEW_ARRAY(type,nelems) \
                             new type[nelems]
#define DBG_DELETE(ptr) delete ptr
#define DBG_DELETE_ARRAY(ptr) delete [] ptr
#endif /*!DEBUG_NEW*/
</pre>
<p>How do we track the allocated pointers to blocks of memory?
First, we record the important aspects of the allocation: the
filename, line number, size of the block, the time for critical
real-time applications, and a pointer to the prefixed header block.
We must also construct, access and modify the record too. I have
called this class the <tt class="classname">BaseMemory</tt> class
and fore-chosen the container type by inserting next and previous
pointers. The BaseMemory is a linked list node. (If this source
code were written in the Java language, then the class would
probably have an interface LinkedListNode.) Here is the BaseMemory
class:</p>
<pre class="programlisting">
class BaseMemory
{
const int MagicID = 0x19FA97CE;
public:
  BaseMemory()  // Required
     : _file(), _line_num(-1),
      _memsize(0), _is_allocated(false),
      _alloc_time(0), 
      _magic_word(MagicID), 
      _prefix_header(0), 
      _prev(0), _next(0),
  {
  }
  BaseMemory( const char* filename, 
              int line_num, 
              PrefixHeader *phdr );
  BaseMemory( const char* filename, 
              int line_num, 
              PrefixHeader *phdr,
              time_t alloc_time );
  ~BaseMemory();
  BaseMemory( const BaseMemory &amp;x  );
  
  // Assignment Operator
  BaseMemory &amp; operator=
    ( const BaseMemory &amp;x  );

  friend bool  operator&lt;
    ( const BaseMemory &amp;x, 
      const BaseMemory &amp;y );

  // Accessor member functions
  const string &amp; file() const 
  { return (_file); }
  const int line_num() const 
  { return (_line_num); }
  const size_t memsize() const 
  { return (_memsize); }
  const bool is_allocated() const 
  { return (_is_allocated); }
  
  // Check Base Memory
  void checkit() const
  {
  // Has the base memory been corrupted? 
  // Throw exception!
  if (_magic_word != MagicID) {
    cerr 
       &lt;&lt; &quot;(*DBGNEW*) base memory corrupted.&quot; 
       &lt;&lt; endl;
    throw BaseMemoryCorrupted();
  }
}

friend class DynamicMemoryController;
    
private:
  string    _file;      // ptr to __FILE__ string
  int      _line_num;    // ptr to __LINE__ string
  size_t    _memsize;    // allocation size
  bool    _is_allocated;    // TRUE, if in use
  time_t    _alloc_time;    // alloc time
  int      _magic_word;    // Magic 
  PrefixHeader *  _prefix_header;
  BaseMemory *  _next;
  BaseMemory *  _prev;
};
</pre>
<p>The <tt class="classname">BaseMemory</tt> class has a very
simple method called checkit() that checks that the object instance
has not been corrupted. The method is not foolproof though. The
operator&lt; is declared for sorting base memory elements. (This
member operator function is a remnant of the my aborted experiments
that used a STL vector container.) <tt class=
"classname">BaseMemory</tt> class has a friend class, which is
called <tt class="classname">DynamicMemoryController</tt>, which
serves as the linked list container.</p>
<p>The controller for the C++ debuggable new and delete is a
SINGLETON. There can only be one process and therefore only one
global scope namespace <tt class="function">new</tt> and <tt class=
"function">delete</tt> manager. So what follows is a straight
application of <i class="firstterm">Meyerism</i> (after Scott Meyer
[<a href="#Meyers">Meyers</a>]). The controller is presented:</p>
<pre class="programlisting">
class DynamicMemoryController {
// This is a SINGLETON for the whole app
private:
  DynamicMemoryController();
public:
  static DynamicMemoryController *
  get_controller()
  {
  if (the_memory_controller == 0) {
    the_memory_controller = new DynamicMemoryController();
    // Add memory dump handler
    atexit( dump_memory_leak );
   }
  return (the_memory_controller);
  }

  static bool initialised();
    
  ~DynamicMemoryController();

  void AddBaseElement( char *file, 
    int line_num, PrefixHeader *phdr );
    
  bool RemoveBaseElement( char *file, 
    int line_num, PrefixHeader *phdr );
    
  BaseMemory * FindBaseElement
    ( PrefixHeader *phdr );

  void PrintLeaks( ostream &amp;out );
private:
  static int the_max_elements;
  static BaseMemory *  the_base_memory;
  static DynamicMemoryController *
    the_memory_controller;
};
</pre>
<p>I draw your attention to the <tt class=
"methodname">get_controller()</tt> private method of the dynamic
memory controller. This member function only ever returns
<span class="emphasis"><em>one and only one</em></span> single
DynamicMemoryController object instance. The first time the memory
controller is generated the function immediately registers the
public function <tt class="methodname">dump_memory_leak()</tt> with
the standard C library's <tt class="function">atexit()</tt>
routine. So that when the program terminates normally or abnormally
(as long it is not a core dump or general protection fault) any
memory leaks are printed to the standard output.</p>
<p>For those of you unfamiliar with Singletons, it is a software
engineering design pattern that appears in many applications.
[<a href="#GoF">GoF</a>] A Singleton is a restricted object, which
is only supposed to be created N number of times. (In our case
N==1.) In C++ , the singleton object has its default constructor
declared private. An alternative public class method creates the
object, which is the so-called point of control. The object class
<tt class="classname">DynamicMemoryController</tt> has a public
declared <tt class="methodname">get_controller()</tt> member
function, which returns a single object, which is statically
declared in the global scope.</p>
<p>The other problem to solve is guaranteeing the order of global
object creation: making sure that the <tt class=
"classname">DynamicMemoryController</tt> exists before we use it in
a function or procedure, or any other global initialisation in any
implementation source file. To achieve this goal a helper class
called <tt class="classname">Dbgnew_init</tt> is used. A static
variable of type <tt class="classname">Dbgnew_init</tt> is declared
as the last statement in the <tt class=
"filename">&lt;dbgnew&gt;</tt> C++ header file. The result of this
last declaration guarantees the creation of the dynamic memory
controller before any other that uses in a normal C++ source file.
Please consult Scott Meyer's Effective C++ book for more
information about the idiom.</p>
<pre class="programlisting">
// Filename:`dbgnew.h'
// Assumed in the private lib namespace.
class Dbgnew_init {
  // Help class to construct &amp; destruct the 
  // `DynamicMemoryController'
  // object instance (SINGLETON)
public:
  Dbgnew_init();
  ~Dbgnew_init();
    
private:
  Dbgnew_init( const Dbgnew_init &amp; );
  Dbgnew_init &amp; operator=( const Dbgnew_init &amp; );
  static unsigned short _count;  
  // The number of `Dbgnew_init'
  // objects currently in existance
};
...
static Dbgnew_init  dbgnew_init;

// static object created for
// source code translation unit
// Filename:`dbgnew.cc'
...
unsigned short Dbgnew_init::_count;

Dbgnew_init::Dbgnew_init()
{
  if ( _count++ == 0 ) {
  // Force the construction of the dynamically
  // allocated `DynamicMemoryController' 
  // singleton. We throw away the pointer.
  DynamicMemoryController::get_controller();
  }
}

Dbgnew_init::~Dbgnew_init()
{
  if ( --_count == 0 ) {
  // Force the destruction of the 
  // DynamicMemoryController' singleton. 
  // We use the returned pointer to delete the
  // instance.
  delete
    DynamicMemoryController::get_controller();
  }
}
</pre>
<p>The static global scope variables in the implementation file are
declared like this:</p>
<pre class="programlisting">
unsigned short Dbgnew_init::_count;
  // The dynamic memory controller's 
  // helper class's counter variable

DynamicMemoryController* 
  DynamicMemoryController::
  the_memory_controller;
// Pointer to the dynamic memory controller 
// singleton object instance
BaseMemory*   
  DynamicMemoryController::
  the_base_memory;
// Pointer to the controller's base memory

int 
  DynamicMemoryController::
  the_max_elements;
</pre>
<p>The registration functions are easy to illustrate. You can see
the internal workings of the C++ preprocessor macros that I
presented at the top of this article. In order to register a
generic pointer to a prefix header pointer to a recognised memory
block requires, first, casting from <tt class="type">void*</tt>
back to the PrefixHeader types. Secondly the prefix header pointer
is recorded by adding it to the linked list maintained by to the
container <tt class="classname">DynamicMemoryController</tt>. A
member function called <tt class="methodname">AddBaseElement()</tt>
performs this function and automatically generates the BaseMemory
object instance (without using new() as will be explained in the
next article).</p>
<pre class="programlisting">
void *_register_memory
  (void *input_ptr, char *file, int line_num )
{
  // Record this allocation
  PrefixHeader *phdr =
    ((PrefixHeader*)input_ptr) - 1;
  DynamicMemoryController::get_controller()
    -&gt;AddBaseElement( file, line_num, phdr );
  return (input_ptr);
}
</pre>
<p>Similarly the unregistration of pointers follows first a similar
recasting to PrefixHeader types. However, the prefix header and
it's corresponding BaseMemory record is removed from the linked
list of the controller by the member function <tt class=
"methodname">RemoveBaseElement()</tt>.</p>
<pre class="programlisting">
void *_unregister_memory
  (void *input_ptr, char *file, int line_num )
{
  // Record this deallocation
  PrefixHeader *phdr = 
    ((PrefixHeader*)input_ptr) - 1;
  diagnose_memory( phdr, file, line_num );
  DynamicMemoryController::get_controller()
    -&gt;RemoveBaseElement(file,line_num,phdr );
  return (input_ptr);
}
</pre>
<p>The function <tt class="function">dump_memory_leak()</tt> is
very simple. For purposes of the article it's report is dumped to
the standard output, but ideally the function would create a
specially named text output file and write the report there.</p>
<pre class="programlisting">
extern &quot;C&quot; void  dump_memory_leak( )
{
  // Print out memory leaks
  DynamicMemoryController::get_controller()
    -&gt;PrintLeaks( cout );
}
</pre>
<p>In the final article I will demonstrate how I created the linked
list of base memory without using hundreds of calls to the global
new operator. I will also describe in further detail the member
functions of the DynamicMemoryController class and it's BaseMemory
class.</p>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e189" id=
"d0e189"></a>Bibliography</h2>
</div>
<div class="bibliomixed"><a name="Pilgrim" id="Pilgrim"></a>
<p class="bibliomixed">[Pilgrim] &quot;Dynamic Memory Integrity&quot;, ACCU/
<span class="citetitle"><i class="citetitle">C Vu 8.5</i></span>,
and &quot;Dynamic Memory Tracking&quot;, ACCU/ <span class=
"citetitle"><i class="citetitle">C Vu 8.6</i></span>, Peter A.
Pilgrim</p>
</div>
<div class="bibliomixed"><a name="Meyers" id="Meyers"></a>
<p class="bibliomixed">[Meyers] &quot;<span class="citetitle"><i class=
"citetitle">Effective C++</i></span>&quot;, Scott Meyers, Addison Wesley
1995.</p>
</div>
<div class="bibliomixed"><a name="GoF" id="GoF"></a>
<p class="bibliomixed">[GoF] &quot;<span class="citetitle"><i class=
"citetitle">Design Patterns</i></span>&quot;, Erich Gamma, Helm et al,
Addison Wesley.</p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
