RetroCausalElectron
RetroCausalElectron

Reputation: 13

Segmentation fault from big arrays

This is a simple code to get an array of a random walk. If I increase the array size anymore it gives me a segmentation fault. I need it to be larger and 2D (like a matrix). How can I do that without getting the error?

#include <iostream>
#include <fstream>
#include <time.h>

using namespace std;

int main(){

    srand (time(NULL));

    int iter = 1000000;
    int x[iter]; x[0] = 0;
    int p = 50;
    int r;

    for(int i=1; i<iter; i++){
        r = rand() % 101;
        if(r<p){
            x[i+1] = x[i] - 1;
        } else if(r>p){
            x[i+1] = x[i] + 1;
        } else if(r=p){
            x[i+1] = x[i];
        }
    }

    ofstream myFile("walk.csv");
    for(int j=0; j<iter; j++){
        myFile << x[j] << "\n";
    }

    myFile.close();

    return 0;
}

Upvotes: 0

Views: 111

Answers (2)

h0tst3w
h0tst3w

Reputation: 114

You’ll need to dynamically allocate the array or make it a global variable. The stack space for that variable is exhausted by that single instruction.

int * x = new int[iter]; //or however you choose to name it
delete []x; //DO NOT FORGET TO DELETE THIS

`

Upvotes: 2

Guillaume Racicot
Guillaume Racicot

Reputation: 41750

To use such a big array, you will need to use dynamic memory. Large array like that cannot be on the stack, it will overflow the stack.

One of the best tool for that is a std::vector:

#include <iostream>
#include <fstream>
#include <vector>
#include <time.h>

using namespace std;

int main(){

    srand (time(NULL));

    int iter = 1000000;
    vector<int> x(iter);

    // This line is a bit redundant since vectors
    // are initialized with zeros by default
    x[0] = 0;
    int p = 50;
    int r;

    for(int i=1; i<iter; i++){
        r = rand() % 101;
        if(r<p){
            // Be careful, here you index outside the array
            // i will go to iter, but you are doing i+1
            // you should spell your for like this:
            // for(int i = 1; i < iter - 1; i++)
            x[i+1] = x[i] - 1;
        } else if(r>p){
            x[i+1] = x[i] + 1;
        } else if(r=p){
            x[i+1] = x[i];
        }
    }

    ofstream myFile("walk.csv");
    for(int j=0; j<iter; j++){
        myFile << x[j] << "\n";
    }

    myFile.close();

    return 0;
}

As you can see, that type from std is really acting just like an array, but has dynamic properties.

Upvotes: 3

Related Questions