vector doesn't initialize

Aug 8, 2010 at 6:55am
Hi all, having a little trouble figuring out why I'm getting a seg fault. I'll post the relevant snippets of code preceded by a quick description.

First, the cloning function. This is where I suspect the problem is. I think the memory for the local object is getting deleted once the function finishes.
1
2
3
4
5
6
7
8
9
10
11
12
13
Matrix* Matrix::clone()
{
    Matrix mat(m_rows, m_cols);
    for (int i = 0; i < m_rows; i++)
    {
        for (int k = 0; k < m_cols; k++)
        {
            mat.set(i, k, m_mat[i*m_cols+k]);
            cout << mat.get(i, k) << endl;
        }
    }
    return &mat;
}


Where the actual seg fault occurs and what calls the method.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
double Matrix::get(const int row, const int col)
{
    return m_mat[row*m_cols+col];
}

void Matrix::debug()
{
    for (int i = 0; i < m_rows; i++)
    {
        for (int k = 0; k < m_cols; k++)
        {
            cout << get(i, k) << " ";
        }
        cout << endl;
    }
}


Now the code from main that starts everything.
1
2
Matrix* cloned_p = mat_p->clone();
cloned_p->debug();


I also tried returning a Matrix from clone() but that's a totally different problem. Any ideas? I'll also be willing to hear random other helpful comments if you're kind enough to offer them. Thanks a ton in advance for insight into the problem.
Aug 8, 2010 at 7:48am
At the end of the function the program automatically call the destructor of its variables. The memory will be freeing, (if you allocate your matrix dynamical, I suppose you've got a delete in ~Matrix() ).
Could try this
1
2
3
4
5
6
7
 Matrix* Matrix::clone(){
    Matrix *mat = new Matrix(m_rows, m_cols);
    //...
    return mat;
}
//or avoid pointers
void Matrix::clone(Matrix &m);


Aug 8, 2010 at 8:02am
another option is to use the copy constructor:
1
2
3
4
5
Matrix* Matrix::clone(){
    Matrix *mat = new Matrix(*this);
 
    return mat;
}
Aug 8, 2010 at 8:04am
Matrix uses the custom destructor. Your advice about Matrix* mat worked perfectly, thanks.
Topic archived. No new replies allowed.