This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Catching memory errors


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@gmail.com> 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 Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]