title: Questions about C++ memory allocation and delete
body: <p>I'm getting a bad error. When I call delete on an object at the top of an object hierarchy (hoping to the cause the deletion of its child objects), my progam quits and I get this:</p>
  
  <pre>*** glibc detected *** /home/mossen/workspace/abbot/Debug/abbot: double free or corruption (out): 0xb7ec2158 ***</pre>
  
  <p>followed by what looks like a memory dump of some kind. I've searched for this error and from what I gather it seems to occur when you attempt to delete memory that has already been deleted. Impossible as there's only one place in my code that attempts this delete. Here's the wacky part: it does not occur in debug mode. The code in question:</p>
  
  <p><pre><code>
  Terrain::~Terrain()
  {
      if (heightmap != NULL) // 'heightmap' is a Heightmap*
      {
          cout &lt;&lt; "heightmap&amp; == " &lt;&lt; heightmap &lt;&lt; endl;
          delete heightmap;
      }
  }
  </code></pre></p>
  
  <p>I have commented out everything in the heightmap destructor, and still this error. When the error occurs, </p>
  
  <pre>heightmap& == 0xb7ec2158</pre>
  
  <p>is printed. In debug mode I can step through the code slowly and</p>
  
  <pre>heightmap& == 0x00000000</pre>
  
  <p>is printed, and there is no error. If I comment out the 'delete heightmap;' line, error never occurs. The destructor above is called from another destructor (separate classes, no virtual destructors or anything like that). The heightmap pointer is new'd in a method like this:</p>
  
  <p><pre><code>
  Heightmap* HeightmapLoader::load() // a static method
  {
     // ....
     Heightmap* heightmap = new Heightmap();
     // ....other code
     return heightmap;
  }
  </code></pre></p>
  
  <p>Could it be something to do with returning a pointer that was initialized in the stack space of a static method? Am I doing the delete correctly? Any other tips on what I could check for or do better?</p>