当我尝试运行我的代码时,它编译没有问题。但是,当我尝试运行它时,我得到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);
首先,你有内存泄漏。为了避免泄漏并进行更好的边界检查,您应该考虑使用std::vector<std::vector<int>>
而不是int**
.
您的崩溃是由于第二次失败。当第二个load
失败时,它返回0,即nullptr
(nullptr
在这种情况下建议使用而不是0)。后来,show
尝试取消引用它nullptr
- 导致分段错误。
如果您坚持使用原始指针,而不是向量,或者第二好的 unique_ptr,那么您必须确保在 失败时load
以及在连续成功调用之间load
(和最后)清除分配。
由于整数 355,第二个调用已损坏。此外,您的列和行似乎被调换了(行被视为列,列被视为行)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句