Lukas Bystricky
Lukas Bystricky

Reputation: 1272

mysterious c++ segmentation fault

I'm new to C++ and am having some difficulty with this simple problem. The following code exhibits some strange behaviour. I'm trying to print a bunch of numbers to a text file and time how long it takes. For smaller n (< 5000), the code runs but the text file that gets created is jibberish. For n > 10000 the program crashes with the error "segmentation fault (core dumped)".

Here is my code in its' entirety:

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

Does anyone have an idea as to the problem?

Upvotes: 0

Views: 188

Answers (1)

Nemanja Boric
Nemanja Boric

Reputation: 22187

As you want to print the integer and the new line into the file, and not to "add" them, this line

resultsfile << i + "\n";

should be

resultsfile << i << "\n";

Next time, compile your program with -g option and run it inside gdb. After running the program, and receiving segfault, type backtrace, so you can see where your code broke. This way segmentation fault will not be so mysterious.

Upvotes: 2

Related Questions