invalid pointer error when trying to return object by value
<p>I have a class, Matrix</p>

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

<p>I have the function addandupdate defined outside as below,</p>

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

    Matrix c(csize, rsize);

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

<p>Then in main, </p>

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

<p>Everything is fine except the line above that is causing to throw a runtime error.</p>

<pre><code>*** 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]
</code></pre>

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