the problem of copy ctor

class A {
int *p;

public:
A(int N){ p = new int[N];}

~A() {delete [] p; p = NULL;}
};

int main() {
A a(5);
A b = a;
}

It fails after the last statement, what's the problem
Last edited on
A a(5);
This creates an A, which allocates 5 ints.
A b = a;
This calls the compiler-generated copy constructor which looks something like this:
1
2
3
A::A(const A &src){
    this->p=src.p;
}

When main() returns, both a and b are destructed. Since both of their 'p's point to the same array, after the first A is destructed, the other's p is no longer valid, so when it's destructed it will produce a segmentation fault.

Always write your own copy constructors if you're doing dynamic allocation.
I just add the copy ctor to the code, it still fails, maybe it's because the memory is not cleared properly, but I don't know how to do that. Besides, can you tell what's tool do you use to add the code as above, thanks.
Last edited on
Are you allocating an array for the new object or did you just copy the example I wrote above?
Topic archived. No new replies allowed.