0

i have a little program that tries to do it but fails

class myclass{
public:
    int * ptr;
    myclass (){
        ptr = new int;
    }
    myclass (const myclass &class_inst){
        ptr = new int;
        *ptr = *class_inst.ptr;
    }
    ~myclass (){
        delete ptr;
    }
};

myclass dosomething (myclass a){
    // make some changes to a
    return a;
}
int main(){
     myclass test1;
     test1 = dosomething (test1);
     return 0;
}

after test1 = dosomething.. is executed, test1's destructor is called. it gets called again at the end of main and that causes a seg fault.

1 way to fix this would be to have dosomething as a member function and use test1.dosomething(). Id like to know what is wrong with the above code.

Thanks!

viraj
  • 59
  • 1
  • 7

2 Answers2

0

You allocate memory for the single int, store the pointer to it to ptr, and then overwrite the same pointer with class_inst's pointer. When destructed both objects try to deallocate the same memory block.

I assume you wanted to copy the contents.

myclass (const myclass &class_inst){
    ptr = new int;
    *ptr = *class_inst.ptr;
}
Blaz Bratanic
  • 2,279
  • 12
  • 17
0

Echoing Mooing Duck's comment about the rule of three, I will try and walk through what happens at each step of your main (apologies for any mangled indentation):

int main(){
     myclass test1; //myclass default ctor called.
                    //ptr assigned a new int (uninitialised)
     test1 = dosomething (test1); //make a copy of test1
                                  //a.ptr is assigned a new int and then assigned class_inst.ptr, losing the original “new int” which will be leaked
                                  //return a copy (call it result) constructed my class of argument a (which is a copy of test 1)
                                  //result.ptr is assigned a new int and then assigned class_inst.ptr, 
                                  //losing the original “new int” which will be leaked
                                  //a goes out of scope, and calls its door which deletes it’s a.ptr, which is pointed to by result.ptr (which in turn is class_inst.ptr) 
 return 0;                        //test1 (which is the same as result above) goes out of scope and tries to delete its ptr member, which is != NULL
                                  //and then you get the seg fault

}

So what you should do is look up the rule of three (aka the big three), think about what happens in the default and copy constructors really hard, and equally so about the destructor.