神秘的c ++分段错误

时间:2013-09-08 20:58:49

标签: c++ g++ segmentation-fault

我是C ++的新手,对这个简单的问题有些困难。以下代码表现出一些奇怪的行为。我正在尝试将一堆数字打印到文本文件中,并计算所需的时间。对于较小的n(<5000),代码运行但是创建的文本文件是乱码的。对于n> 10000程序崩溃,出现错误“segment fault(core dumped)”。

以下是我的全部代码:

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

有没有人知道这个问题?

1 个答案:

答案 0 :(得分:2)

由于您要将整数和新行打印到文件中,而不是“添加”它们,此行

resultsfile << i + "\n";

应该是

resultsfile << i << "\n";

下次,使用-g选项编译您的程序,并在gdb内运行它。运行程序并接收段错误后,键入backtrace,以便查看代码中断的位置。这样分段错误就不那么神秘了。

相关问题