Re: Catching memory errors

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

 



Bala,

   I don't see a question or a point of failure.  You'll have to be
more specific.

   When did it crash?  What is the copy constructor?  What part is the
*strange behavior*?

corey

On 5/21/05, Bala B K <bkbsub@xxxxxxxxx> wrote:
> 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&amp; 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-&gt;getb1();
>         delete b;
>         b = NULL;
>         B* c = new B();
>         a-&gt;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