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(constint row, constint 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;
}
}
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.
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