Когда я пытаюсь запустить мой код, он без проблем компилируется.Однако, когда я пытаюсь запустить его, я получаю line x: segmentation fault
, где x - строка, на которой предположительно находится ошибка, но она меняется на +1 каждый раз, когда я пытаюсь снова запустить программу, что кажется странным.Ниже приведен соответствующий код:
#include <iostream>
#include <fstream>
#include <string>
#include "image.h" // Has the prototypes for the functions
using namespace std;
int** load(string imageFile, int &length, int &height) {
ifstream file(imageFile);
if(file.is_open()) {
file >> length;
int** array = new int*[length];
file >> height;
for(int i = 0; i < length; i++) {
array[i] = new int[height];
for(int j = 0; j < height; j++) {
file >> array[i][j];
if(array[i][j] > 255 || array[i][j] < 0) {
cout << "Image is corrupted." << endl;
file.close();
return 0;
}
}
}
file.close();
return array;
}
else {
cout << "Unable to open file." << endl;
return 0;
}
}
void show(int **image, int length, int height) {
cout << "The height of the matrix is: " << height << endl;
cout << "The length of the matrix is: " << length << endl;
cout << "The matrix is: " << endl;
for(int i = 0; i < length; i++) {
for(int j = 0; j < height; j++) {
cout << " " << image[i][j];
}
cout << endl;
}
}
int main() {
int height = 0;
int length = 0;
int **image = load("../resource/imagecorrupted.txt", length, height);
image = load("../resource/image.txt", length, height);
show(image, length, height);
}
Это вывод:
Image is corrupted.
Image is corrupted. //Not sure why this shows twice to be honest
The height of the matrix is: 8 // but that seems like the least of my worries
The length of the matrix is: 10
The matrix is:
-bash: line xx: xxxxx Segmentation fault
Не уверен, что может быть причиной, любая помощь приветствуется!
РЕДАКТИРОВАТЬ:
Я полностью забыл показать, какими должны быть входные данные.Приношу извинения.Вот они:
10 8
0 255 255 255 0 0 255 255 255 0
255 0 255 255 0 0 255 255 0 255
255 255 0 255 255 255 255 0 255 255
255 255 255 0 255 255 0 255 255 255
255 255 255 355 0 0 255 255 255 255
255 255 255 255 0 0 255 255 255 255
255 255 255 0 255 255 0 255 255 255
0 0 0 255 255 255 255 0 0 0
Это то, что содержится в image.txt
.imagecorrupted.txt
идентично, с одним значением, переключенным с 255 на 355 (оно намеренно означает сбой).10
и 8
- это длина / высота матрицы.
РЕДАКТИРОВАТЬ 2:
Попытка добавить функцию delete
между каждым вызовом load
, но безрезультатно, хотя я уверен, что здесь что-то не получается.Используемый код:
void free(int **image, int &length, int &height) {
if(image) {
for(int i = 0; i < length; i++) {
if(image[i]) {
delete[] image[i];
}
}
delete[] image;
}
}
И то, что я сделал в основном, было:
int **image = load("../resource/imagecorrupted.txt", length, height);
free(image, length, height);
image = load("../resource/image.txt", length, height);