神秘的 C++ 分段错误
mysterious c++ segmentation fault
我是C++新手,在这个简单的问题上遇到了一些困难。下面的代码表现出一些奇怪的行为。我正在尝试将一堆数字打印到文本文件中,并计算需要多长时间。对于较小的 n (<5000),代码运行,但创建的文本文件是乱码。对于 n> 10000,程序崩溃并显示错误"分段错误(核心转储)"。
这是我的完整代码:
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
using namespace std;
double listN(int n)
{
clock_t start = clock();
ofstream resultsfile;
resultsfile.open("Number.txt");
for (int i = 0; i < n; i++)
{
resultsfile << i + "n";
}
resultsfile.close();
return (1000 * (clock() - start)/(double) CLOCKS_PER_SEC);
}
int main()
{
const int NUM_RUNS = 20;
double time = 0;
int n;
cout << "Enter the value n:";
cin >> n;
for (int i = 0; i < NUM_RUNS; i++)
{
time += listN(n);
}
cout << time / NUM_RUNS <<endl;
return 0;
}
有人对这个问题有想法吗?
由于您要将整数和新行打印到文件中,而不是"添加"它们,因此此行
resultsfile << i + "n";
应该是
resultsfile << i << "n";
下次,使用-g
选项编译程序并在 gdb
中运行它。运行程序并收到段错误后,键入 backtrace
,以便您可以看到代码中断的位置。这样分割错误就不会那么神秘了。
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 我是如何在这段代码中出现分段错误的
- 创建结构的数组时遇到分段错误
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 在 c++ 中实现 Trie 时出现分段错误
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 为什么我遇到分段错误?
- 动态类的分段错误(家庭作业问题)
- 分段错误 - 读取初始化指针的数组
- 如何摆脱C ++中的分段错误错误?
- 使用 CTYPE 时出现分段错误
- 为什么代码给出分段错误?