gpt4 book ai didi

c++ - 尝试打印/加载二维数组时出现段错误

转载 作者:行者123 更新时间:2023-11-28 01:24:04 25 4
gpt4 key购买 nike

当我尝试运行我的代码时,它编译没有问题。然而,当我尝试运行它时,我得到了 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);
}

这是输出:
图像已损坏。
图像已损坏。//老实说,不知道为什么这会显示两次
矩阵的高度是:8//但这似乎是我最不担心的
矩阵的长度为:10
矩阵是:
-bash: line xx: xxxxx 段错误

不确定是什么原因造成的,如有任何帮助,我们将不胜感激!

编辑:

我完全忘了显示输入的含义。我道歉。他们来了:
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(这是故意要失败的)。 108 是矩阵的长度/高度。

编辑 2:

尝试在每个 load 调用之间添加一个 delete 函数,但无济于事,尽管我确信这里有些东西我没有得到。这是使用的代码:

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;
}
}

我在 main 中所做的是:

 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 -- 导致段错误。

如果您坚持使用原始指针,而不是 vector ,或者次优的 unique_ptr,那么您必须确保在 load 失败时清理分配。 , 以及对 load 的连续成功调用之间(最后)。

编辑

由于整数 355,第二次调用已损坏。此外,您的列和行似乎已调换(行被视为列,列被视为行)。

关于c++ - 尝试打印/加载二维数组时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54761366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com