[PLUG] C++ question

jason justman jason at jasonjustman.com
Tue Mar 20 01:49:15 UTC 2007


Hmm, it looks like a typo of some sort to me - an introductory book on 
c++ probably isn't trying to show you potental buffer/doublefree bugs.  
You've lucked out, because usually making an assignment to a * that has 
been deleted might cause a segfault.

In general, calling delete on a * that has already been deleted is a bad 
thing - glibc has detected this and is trying to protect you from 
yourself - http://www.owasp.org/index.php/Double_Free


Having said all that, i'm almost 100% sure you are missing the following 
inbetween:

delete pHeap;
if (pHeap == NULL)


 pHeap = new int;

The author is probably trying to show you how to delete and create a new 
*, rather than segmentation faults in your program.

Thanks,
J


Sean Whitney wrote:
> 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
>
>   



More information about the PLUG mailing list