0

I have a class, Matrix

class Matrix
{
private:
    int cols;
    int rows;
    int **matrix;
public:
    //constructors and methods
    friend Matrix addandupdate(Matrix a, Matrix b); 
}

I have the function addandupdate defined outside as below,

Matrix addandupdate(Matrix a, Matrix b)
{
    int rsize = a.rows;
    int csize = a.cols;

    Matrix c(csize, rsize);

    for(int i=0; i<rsize; i++)
    {
        for(int j=0; j<csize; j++)
        {
            c.set(i,j,a.matrix[i][j]+b.matrix[i][j]);
        }
    }
    return c;
}

Then in main,

Matrix x(c, r);
//filling values in x
//printing x
Matrix newx = addandupdate(x, x);    //something is not right here
//printing newx

Everything is fine except the line above that is causing to throw a runtime error.

*** glibc detected *** ./a.out: munmap_chunk(): invalid pointer: 0x085c6020 ***
======= Backtrace: =========
/lib/i386-linux-gnu/libc.so.6(+0x73e42)[0x183e42]
/lib/i386-linux-gnu/libc.so.6(+0x74525)[0x184525]
/usr/lib/i386-linux-gnu/libstdc++.so.6(_ZdlPv+0x1f)[0x84d51f]
./a.out[0x8048c69]
./a.out[0x8048b05]
/lib/i386-linux-gnu/libc.so.6(__libc_start_main+0xf3)[0x1294d3]
./a.out[0x8048751]

I'm writing C++ code after a long time. Please excuse me if it's something silly.

John Eipe
  • 10,922
  • 24
  • 72
  • 114
  • 1
    You're probably violating the [rule of three](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three). Can you show your constructors? – Mysticial Aug 02 '12 at 18:05

1 Answers1

1

Matrix newx = addandupdate(x, x); calls the copy constructor, which you haven't implemented, and you need since a shallow copy isn't enough in your case.

You'll also need an assignment operator and destructor.

Or, as Mark pointed out, replace int **matrix; with std::vector<std::vector<int> >.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625