I want to fill a double pointer 2D array with the values from a CSV. I don't want to read the csv file to get the size of the array before filling it and I want to do it with pointers and not std::vector. My current code is this
std::pair<int, int> readFile(const std::string &filename, int **matrix) {
std::fstream file{filename, std::ios::in};
if (file.is_open()) {
std::string line{};
int col{0};
int row{0};
while (std::getline(file, line)) {
// Check how many cols there are
int len = std::count(begin(line), end(line), ',') 1;
// Allocate a vector with size the cols found before
int *tmp = reinterpret_cast<int *>(calloc(len, sizeof(int)));
col = 0;
// Fill the temp vector with the read numbers
while (line.size() > 0) {
int num{-1};
// This is just to parse a number, nothing special here
if (line.find(",") != std::string::npos) {
num = std::stoi(line.substr(0, line.find(",")));
line.erase(0, line.find(",") 1); // 1 to also delete delimiter
} else {
num = std::stoi(line);
line = ""; // Set line empty to go out of the while
}
tmp[col] = num;
col ;
}
// Assign the temporal vector to a row of the matrix
matrix[row] = tmp;
row ;
}
return {row, col};
}
std::cout << "Failed to open file at " << filename << std::endl;
return {-1, -1};
}
int main() {
int **matrix;
auto shape = readFile("file.csv", matrix);
for (size_t row = 0; row < shape.first; row ) {
for (size_t col = 0; col < shape.second; col ) {
std::cout << matrix[row][col] << " ";
}
std::cout << std::endl;
}
// Free the pointers
for (size_t row = 0; row < shape.first; row ) {
free(matrix[row]);
}
}
My current result is:
0 0 -751362032 21853 1
2 3 4 2 3
2 1 3 4 5
3 2 1 4 3
2 2 2 2 2
free(): double free detected in tcache 2
Aborted (core dumped)
It seems that the fist tmp vector is being freed before the print (the rest of the values are right). Any idea what I'm missing?
CodePudding user response:
You're passing matrix to your readFile function uninitialized, and then go on and access it with matrix[i]=tmp. That can cause all kinds of issues since you're working with memory that doesn't belong to you.
