allocating in 2-d is nothing but trouble.
did you know you can define operators in c++? Then p4 = p2+p3 becomes legal syntax.
you have some very subtle and annoying memory problems with your approach.
sum creates w.
sum destroys w when it ends. but it returned it as well.
the default assignment operator is going to copy the pointers, which were deleted, to p4 and then it will blow up.
I highly recommend that when you delete a pointer, you set it to null immediately.
I think you will have to make your own assignment operator, and due to that, follow rule of 3 etc as your program grows. If you keep to this approach. If you move to my recommended vector approach, you won't need all this memory juggling.
the quick fix for what you have is to make sum use a pointer instead.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
matrix* sum(matrix &u,matrix &v)
{
matrix *w = new matrix(u.M,u.N);
//w[0].name = "W"; //to find the bug I had each matrix tell me about its dtor activity by naming each object.
for (int i=0;i<u.M;i++)
{
for (int j=0;j<u.N;j++)
{
w[0].alloc(i,j,u.read(i,j) + v.read(i,j));
}
}
return w;
}
and down in main:
matrix *p5 = sum(p3,p3);
p5[0].print();
delete p5;
|
the above code fixes the crashes and works, but its not a clean fix, its a minimal change fix. It just prevents w's matrix object from being auto destroyed, forcing you to do that yourself down in main.
do you understand that w deleted its pointers, but p4 uses those pointers, and that goes all kinds of wrong? These objects CANNOT share pointers (cannot allow assignment operator to copy the pointers) because they destruct delete them. When a = b then a's p == b's p and whichever one dies first the other one is going to have problems after that.... !
classes with pointers (dynamic memory) cause nothing but trouble. I recommend a do-over with a 1-d vector for p, and the bulk of your problems will clear up quickly. Actually, pointers for dynamic memory are trouble, and best not to do that.