我收到分段错误(核心转储)错误,但仅当我的一半代码运行时

I get a segmentation fault (core dumped) error but only when half my code runs

本文关键字:错误 我的 代码 一半 运行时 分段 转储 核心      更新时间:2023-10-16

这段代码的目标是操作一个ASCII"图像",它以一个很长的字符串的形式出现,我在不同的行上打印出来。

.............  
.............  
.XXX.....X...  
.XXX.....X...  
.XXX.........  
.XXX.........  
.XXXXXXX.....  
.XXXXXXX.....  
.XXXXXXX.....  
...........  

看起来像这样

#include <iostream>
#include <iomanip>
#include <algorithm>
#include <fstream>
#include <vector>
#include <string>
#include <cassert>
int main (int argc, char* argv[]) {
    std::fstream img(argv[1]);
    std::vector<char> path;
    char x;
    while (img >> x) {
        path.push_back(x);
    }
    for (char i = 0; i < path.size(); ++i) {
        if (i%13==0) {
            std::cout << path[i] << std::endl;
        }
        else {
            std::cout << path[i];
        }
    }
    std::string replace = "replace";
    std::string dilation1 = "dilation";
    std::string erosion1 = "erosion";
    std::string floodfill1 = "floodfill";
    char old_char = argv[4][0];
    char new_char = argv[5][0];
    if (argv[3] == replace) {
        for (char n=0; n<path.size(); ++n) {
            if(path[n]==old_char) {
                path[n]=new_char;
            }
        }
        for (char i = 0; i < path.size(); ++i) {
            if (i%13==0) {
                std::cout << path[i] << std::endl;
            }
            else {
                std::cout << path[i];
            }
        }
    }
    if (argv[3] == dilation1) {
        std::cout << "this is ok" << std::endl;
    }
}

这是我的代码。代码的替换部分旨在将其作为控制台的输入

./image_processing.out input4.txt output4_replace.txt replace X O

并将 X 替换为 O,它有效。但是,我转到膨胀函数,该函数将其作为控制台的输入。

./image_processing.out input4.txt output4_dilation.txt dilation X

不管它做什么。然而,我什至还没有走那么远,因为每当我尝试使用第二个"if"语句运行代码时,我都会得到这个

.............  
.............  
.XXX.....X...  
.XXX.....X...  
.XXX.........  
.XXX.........  
.XXXXXXX.....  
.XXXXXXX.....  
.XXXXXXX.....  

分段故障(核心转储)

我不知道它为什么要这样做,也不知道为什么它只到最后一行。当我注释掉第二个 if 语句时,代码运行良好;但是,它只会替换。

像这样运行程序时:

./image_processing.out input4.txt output4_dilation.txt dilation X

只有 5 个参数,有效索引为 0 - 4。 该行:

char new_char = argv[5][0];

正在读取通过 argv 数组的末尾,因为这假设有 6 个参数。