mrz
mrz

Reputation: 1872

Array of Struct pointers, getting segfault

I get segfault for the following:

myclass.h

class myclass
{
    struct stuSomething
    {
        ...
        stuSomething(){...}
    };

public:
    static myclass* Instance()
    {
        if (!instance)
            new myclass();
        return instance;
    }
    void myclass:someFun();

private:
    static myclass *instance;
    myclass();
    stuSomething *stuStack[SAMPLE_QUANTITY];
};

myclass.cpp

myclass* myclass::instance;
myclass::myclass()
{
    for(int i = 0; i < SAMPLE_QUANTITY; i++)
        this->stuStack[i] = NULL;
    instance = this;
}

myclass::someFun()
{
    for(int i = 0; i < SAMPLE_QUANTITY; i++)
        if(this->stuStack[i] != NULL) // I get segfault here! for i = 0
            ...
}

But wierd enuogh, when I put

for(int i = 0; i < SAMPLE_QUANTITY; i++)
    if(this->stuStack[i] != NULL) 
        ...

in the constructor right after I fill in the stuStack I dont get segfault.

I feel like there is something obvious I'm missing. What causes the problem?

Upvotes: 1

Views: 60

Answers (1)

gomons
gomons

Reputation: 1976

Check this pointer, it can be invalid.

Upvotes: 1

Related Questions