神秘的 C++ 分段错误

mysterious c++ segmentation fault

本文关键字:分段 错误 C++      更新时间:2023-10-16

我是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 ,以便您可以看到代码中断的位置。这样分割错误就不会那么神秘了。