JamesCs15
JamesCs15

Reputation: 27

c++ OpenGL Segmentation Fault

So, this is a part of my code. I have a class named Polygon with an array to keep my coordinates.

class Polygon{
private:
    GLint Vertices[][2];


public:
    Polygon(){
        GLint** Vertices = new GLint*[20000];
        for (int j=0; j<20000; j++){
            Vertices[j] = new GLint[2];
        }
    }

    void setCoord(int m, GLint x, GLint y){
        Vertices[m][0] = x;
        Vertices[m][1] = y;
    }
};

I try to compile my code and when I try to put my first coordinates in the array in the setCoord() function (when m is 0), I have a segmentation fault error.

Don't know why. Hope you guys will help. Please don't tell me about vectors. I'm not familiar with this technique, and I haven't much time to learn it as my project has to be finished in 4 days.

Thank you!

Upvotes: 1

Views: 161

Answers (1)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

GLint** Vertices = new GLint*[20000];

is a local variable declaration in the Polygon() constructor, and shadows your Vertices class member declaration. Everything allocated there is lost (leaks) after the constructor returns.

You're accessing uninitialized memory in setCoord() thus it crashes.

Change declaration of vertices and constructor in the following way

class Polygon{
private:
    GLint** Vertices; // <<<<<< Change declaration


public:
    Polygon(){
        Vertices = new GLint*[20000]; // <<<<<< Remove GLint**
        for (int j=0; j<20000; j++){
            Vertices[j] = new GLint[2];
        }
    }
};

A side note

"Please don't tell me about vectors. I'm not familiar with this technique, and I haven't much time to learn it as my project has to be finished in 4 days."

I'd suppose use of std::vector<> might be far easier to learn, than getting around and handling all of the obstacles of dynamic memory management right on your own. Good luck!

Upvotes: 4

Related Questions