I am trying to allocate a 2D array inside AllocateMatrix and return it but when I use the returned 2D array I get a segfault. My question is, why is it seg faulting and how do I fix it to where I can pass it and use it in other functions? fileTest is just a txt file with row next line column next line and then the matrix with one space on each column and a new line for each row.
class Matrix
{
public:
Matrix();
~Matrix();
double** AllocateMatrix(unsigned rows, unsigned columns);
Matrix(std::string filePath);
private:
unsigned rows_;
unsigned columns_;
};
Matrix::Matrix(std::string filePath)
{
std::ifstream matrixFile;
try
{
matrixFile.open(filePath);
if(matrixFile.fail())
throw "Failed to open file.";
std::cout << "Starting read file...\n";
matrixFile >> rows_;
std::cout << "rows: " << rows_ << "\n";
if(rows_ < 0)
throw "Number of rows cannot be negative.";
matrixFile >> columns_;
std::cout << "columns: " << columns_ << "\n";
if(columns_ < 0)
throw "Number of columns cannot be negative.";
double** array2D;
array2D = AllocateMatrix(rows_, columns_);
for(uint64_t i = 0; i < rows_; i )
{
for(uint64_t j = 0; j < columns_; j )
{
std::cout << i << " " << j << " " << array2D[i][j] << "\n"; // seg fault here
}
}
std::cout << "Finished file read" << std::endl;
matrixFile.close();
}
catch(const char* message)
{
std::cerr << message << std::endl;
rows_ = 0;
columns_ = 0;
return;
}
}
double** Matrix::AllocateMatrix(unsigned rows, unsigned columns)
{
try
{
double** matrix = new double *[rows];
for(unsigned i = 1; i <= rows; i )
{
matrix[i] = new double[columns];
}
for(unsigned i = 1; i <= rows; i )
{
for(unsigned j = 1; j <= columns; j )
{
matrix[i][j] = 0;
std::cout << "i: " << i << " j: " << j << " value: " << matrix[i][j] << "\n";
}
}
matrix = result_;
std::cout << "Returning 2D Array\n";
return matrix;
}
catch(const std::bad_alloc&) {
std::cerr << "Bad allocation." << std::endl;
return nullptr;
}
}
int main()
{
Matrix matrixOne("fileTest.txt");
return 0;
}
CodePudding user response:
try not using C style pointers, dont use C style pointers. your problem is a usre error. use std::vector instead of using double pointer because is big issue, if have use it then do this: double* array2d[array_sz]; as for not memleak.
CodePudding user response:
I suspect this line is the wrong way round
matrix = result_;
I assume result_ is meant to be a calls field (it isnt but it looks like it)
But here you move unitialized value to 'matrix' which is a pointer the memory you just allocated and initlaized. So you lost any use of that new matrix.
You surely mean
result_ = matrix;
but you should be using
std::vector<std::vector<int>>
life will be a lot simpler then