title: What is the very last place where you can execute logic in a Windows executable?
body: <p>In my application, I want to execute logic at the very last moment.  The later, the better.</p>
  
  <p>The reason for this is that I keep track of certain elements in my application (data structures, resources, ...), and at the end of the application, a routine looks at these elements and reports if they were not correctly closed, freed, deleted, ...</p>
  
  <p>Until now, we did this using several tricks.</p>
  
  <p>The first trick was to overrule the _heap_term function of the C run time (and some other functions as well in the C Run Time).  The advantage was that this worked very well, but was limited to applications in which the CRT was statically linked in.</p>
  
  <p>The second trick was to define a global variable like this:</p>
  
  <pre><code>#pragma init_seg(lib)
  GlobalApplicationManager s_globalApplicationManager;
  </code></pre>
  
  <p>The pragma makes sure that this global variable is constructed before all other global variables, and - more important - that it is destructed after all other global variables.
  This way, we can put the checking logic in the destructor of this class.</p>
  
  <p>Problem is that starting from Windows 7 the destructor is not called anymore in some situations.  At this moment it is not clear what influences this, but we are sure that it is not called if we make a successful Oracle connection in our application.</p>
  
  <p>What other tricks are there to execute code as late as possible in an application?</p>