[PLUG] C++ question

Sean Whitney sean.whitney at gmail.com
Tue Mar 20 00:39:46 UTC 2007


I'm working my way through an older C++ programming book and have found
an error that I can't explain with what the book is expressing.

This program:

#include <iostream>

using namespace std;

int main()
{
 int localVariable = 5;
 int * pLocal = &localVariable;
 int * pHeap = new int;
 if (pHeap == NULL)
    {
        cout << "Error! No memory for pHeap!\n";
    }
    *pHeap = 7;
    cout << "localVariable: " << localVariable << "\n";
    cout << "*pLocal: " << *pLocal << "\n";
    cout << "*pHeap: "  << *pHeap  << "\n";
    delete pHeap;
    if (pHeap == NULL)
       {
           cout << "Error! No memory for pHeap!\n";
        }
    *pHeap = 9;
    cout << "*pHeap: " << *pHeap << "\n";
    delete pHeap;

}

is supposed to be displaying how to delete pointers using delete,
wherein it will release the free memory, but the pointer *pHeap is still
local and as such still exists and can be reassigned a new free memory
location.  However under g++ anytime both delete statements are present,
the program will compile but produce the following error.

localVariable: 5
*pLocal: 5
*pHeap: 7
*pHeap: 9
*** glibc detected *** double free or corruption (fasttop): 0x0804a008 ***
Aborted

Commenting out either delete statements removes the error.

I have discovered that C++ has changed a bit since the book was written,
so I've made a few modifications to the program (namely using using
namespace std; and int main () instead of void main()).  Anyone care to
explain why error occurs?


Sean

-- 
<i> </i>




More information about the PLUG mailing list