为什么会出现此错误?- 分段错误(核心转储)
Why this error? - Segmentation fault (core dumped)
我的代码编译得很好。我正在使用连接到的另一台服务器运行和编译它。当我运行它时,我收到此错误,说 - 分段错误(核心转储(。当我在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上崩溃(,您只是[不]走运。该程序不需要崩溃;它的行为是不确定的。相反,它本可以召唤一位才华横溢的天才来回答你关于堆栈溢出的问题。哦......等等... ;)
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 为什么我使用 std::copy() 收到运行时错误(分段错误)?
- 为什么我的代码包含错误分段错误(核心转储)?
- 为什么会出现此错误?- 分段错误(核心转储)
- 意外的运行时错误(分段错误)
- C++将文本文件读入数组,运行错误:分段错误
- mmap 错误:分段错误/指针无效错误
- 在我的代码中找不到错误....分段错误
- 错误:分段故障(核心转储)阵列
- 用string.h将错误分段到队列中
- c++字符串流转换错误:分段错误
- 为什么我的代码显示错误分段错误(核心转储)