Catching memory errors

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi,

Recently I experienced a very strange behaviour with C++ (g++ 4.0.0,
g++ 3.4.1 and g++ 3.3.3) when I made a mistake and deleted a pointer
twice. Here is what I did:

class B {
// class definition.
};

class A {
        B* b1;
        B* b2;

        A (const A& a) { // copy constructor (DEEP COPY) };
        // Some get and set methods for b1, b2
        void setb1(const B* b) {
                if ( b1 )
                        delete b1;
                b1 = b;
        }
        ...
        ...
};

void myfunc(A* a) {
        B* b = a->getb1();
        delete b;
        b = NULL;
        B* c = new B();
        a->setb1(c);
}

A* a = new A();
myfunc(a);



Now, after the call to myfunc(), if I did this:

A* a1 = new A( *a ); // Call the copy constructor


Then the pointers b1 and b2 inside a1 point to the SAME memory location! 

The program worked as expected when compiled with the xlC
compiler and gave seg faults when compiled with g++ (3.4.1 and 4.0.0).
It is good that when I compile it with g++ I get an error (so that I
fix the buggy code), but it would be nice if g++ could catch it during
run time.

Thanks
Bala


[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux