C++ How to store million objects into array with no segmentation fault

Viewed 306

How can I store million objects into array without error? I'm playing with a 3dEngine in C++ , all works nice and fast but i can't add more than 50K Objects . Object contains 3 vector and colors and some useful method . Some Help ?

enter image description here

#include <iostream>

using namespace std;

class Myc{
    public:
    double x,y,z;
    Myc(double _x=0 ,double _y=0,double _z=0){
        x=_x;y=_y;z=_z;
    }
};

int main(){
    int i; 
    int N=151000;
    Myc pts[N];
    for (i=0;i<N;i++){
        pts[i] = Myc(1,1,1);
    }
    
    cout << pts[999].x <<endl;
    return 0;
}

output:

1                                                                                                                                                                                                                                                                                                                                                                              
...Program finished with exit code 0 

But using int N=1151000;

the output is :

Segmentation fault (core dumped)   

How can I store million objects into array without error? Thanks .

3 Answers

You can allocate the memory on the heap (dynamically allocate it). Currently you are getting stack overflow.

Another way is to do: ulimit -s unlimited on any Linux system to increase the stack size but I advise you to go with the first option.

You can use a std::vector like this:

#include <vector>

class Myc{
    public:
    double x,y,z;
    Myc(double _x=0 ,double _y=0,double _z=0){
        x=_x;y=_y;z=_z;
    }
};

int main(){
    int i; 
    int N=151000;

    std::vector<Myc> pts(N); // stores its data in the free store (heap)

    for (i=0;i<N;i++){
        pts[i] = Myc(1,1,1);
    }
    
    cout << pts[999].x <<endl;
    return 0;
}

A std::vector stored its internal array on the free store (heap) which has a lot more memory that the function stack, which is where local variables like your array are kept.

use a std::vector and insert calling the pts.emplace_back method

int main(){
    int i; 
    int N = 9999999;
    std::vector<Myc> pts;
    for (i = 0; i < N; i++)
    {
        pts.emplace_back(Myc(1, 1, 1));
    }
    
    cout << pts[999].x <<endl;
    return 0;
}
Related