John Eipe
John Eipe

Reputation: 11226

invalid pointer error when trying to return object by value

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.

Upvotes: 0

Views: 395

Answers (1)

Luchian Grigore
Luchian Grigore

Reputation: 258618

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> >.

Upvotes: 1

Related Questions