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.