为什么会出现此错误?- 分段错误(核心转储)

Why this error? - Segmentation fault (core dumped)

本文关键字:错误 分段 核心 转储 为什么      更新时间:2023-10-16

我的代码编译得很好。我正在使用连接到的另一台服务器运行和编译它。当我运行它时,我收到此错误,说 - 分段错误(核心转储(。当我在Mac上本地编译和运行时,它可以完美运行,只是当我使用levi(我们用来提交文件的虚拟机(时则不然。我该怎么做才能不收到此错误消息并运行我的代码?这是我的代码:

//
//  ChaseGraingerSection6.cpp
//
//  Created by Chase Grainger on 3/19/18.
//
// I typed all of this code on my own and did
// not copy any code from any outside sources.
#include <iostream>
#include <fstream>

int main() {
    const int my_dimension = 10; // dimension of 'my_array'
    std::string my_array[my_dimension]; // array of fixed amount of strings
    int x = 0; // used to add lines of text form 'word.txt' to 'my_array'
    int y = 0; // used when reversing array values
    int num_of_lines = 0; // keeps track of # of lines in text file[s]
    std::string text; // used when reading lines from 'word.txt'
    std::string my_reversed_array[num_of_lines]; // reversed order array
    std::ofstream outData; // output stream 'outData'
    std::ifstream inData; // input stream 'inData'
    inData.open("word.txt"); // opens input stream
    while (getline(inData, text)) { // runs through each line in 'word.txt'
        my_array[x] = text; // sets index value of array to line in text file
        num_of_lines += 1;
        x += 1;
    }
    inData.close(); // closes input stream
    // at this point, my_array has the text needed
    outData.open("chase.txt");
    for (x = num_of_lines - 1; x >= 0; x--) { // assisngs values in reverse order from one array to another
        my_reversed_array[x] = my_array[y];
        y += 1;
    }
    for (x = 0; x <= num_of_lines - 1; x++) {
        outData << my_reversed_array[x] << std::endl;
    }
    outData.close();
}
int num_of_lines = 0;
std::string my_reversed_array[num_of_lines];

这实际上不是有效的C++,但在支持可变长度数组作为扩展的编译器上,这会创建一个零大小的数组。

现在,无论你使用哪个编译器,如果你改变num_of_lines,这个数组以后不会神奇地改变大小;那艘船已经航行了。

所以,每当你写信给my_reversed_array,你是在写不属于你的内存。

您将需要动态分配(或std::vector(,以便您可以创建一个具有运行时边界的数组 - 并且在知道这些边界是什么之前不要这样做。

要回答您的下一个问题(为什么这没有在您的Mac上崩溃(,您只是[不]走运。该程序不需要崩溃;它的行为是不确定的。相反,它本可以召唤一位才华横溢的天才来回答你关于堆栈溢出的问题。哦......等等... ;)