Microsoft KB Archive/132893

From BetaArchive Wiki
< Microsoft KB Archive
Revision as of 10:02, 21 July 2020 by X010 (talk | contribs) (Text replacement - """ to """)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Knowledge Base

PRB: Exceptions Thrown During Construction Can Orphan Memory

Article ID: 132893

Article Last Modified on 7/5/2005


  • Microsoft Visual C++ 2.0 Professional Edition
  • Microsoft Visual C++ 2.1
  • Microsoft Visual C++ 4.0 Standard Edition
  • Microsoft Visual C++ 4.2 Enterprise Edition
  • Microsoft Visual C++ 4.2 Professional Edition
  • Microsoft Visual C++ 5.0 Enterprise Edition
  • Microsoft Visual C++ 5.0 Professional Edition

This article was previously published under Q132893


Memory that is dynamically allocated in a constructor can be orphaned when an exception is thrown in the constructor.


When inside a constructor, the object is partially constructed, so the destructor is not called. While automatic data is freed during stack unwinding, memory that is dynamically allocated is not properly cleaned up.


Two-phased construction of objects resolves this problem (see the following code sample). This way, the object is fully constructed, so when it is deleted, cleanup is handled correctly.

Sample Code

The following sample code shows both single- and two-phased construction for a class.

   /* Compile options needed: /MT /GX
   // Change the following line into a comment to show the problem:
   // Include the MFC debug memory allocation functions. You will see the
   // memory leaks reported by MFC when the application terminates when you
   // run the program in the Visual C++ debugger.
   #include "afx.h"
   #define new DEBUG_NEW
   class A
      char *x;
      A() // This code doesn[ASCII 146]t clean up.
         x = new char[10]; // x will be orphaned.
         throw int(1);
      A() // This code cleans up fine.
         // Initialize automatic variables here.
      void Create()
         // Initialize dynamic members here.
         x = new char[10];
         throw int(1);
         delete [] x;
   void main()
      A *a;
         a=new A;
   // Do memory allocation in Create() when doing two-phased construction.
         delete a;

Additional query words: 9.0 9.1 9.00 9.10

Keywords: kbprb kbcodegen kbcpponly kbcode kbcompiler KB132893