Page 1 of 1

RESOLVED:segfault error; help please?

Posted: Sun Jan 11, 2009 5:54 am
by rolland
Maybe it's because I've been devving all night, but this is beyond me... Whenever I run my project, it gets to the constructor and calls updateStates(). It segfaults when trying to access the controller, whether it comes to the hat, axes, or buttons first.

typedef'd struct called myController...

Code: Select all

typedef struct
{
    Sint16 axis[4];
    bool button[12];
    Uint8 hat;
} myController;
class header called inputClass

Code: Select all

class inputClass
{
    private:
        SDL_Joystick* joystick;
        myController* controller;
    public:
        inputClass();
        ~inputClass();
        void updateStates();
        myController* getStates();
};
source code

Code: Select all

inputClass::inputClass()
{
    SDL_Init(SDL_INIT_JOYSTICK);
    joystick = SDL_JoystickOpen(0);
    //std::cout << "joystick open" << std::endl;
    updateStates();
}

void inputClass::updateStates()
{
    for(int i = 0; i < 4; i++)
    {
        controller->axis[i] = SDL_JoystickGetAxis(joystick, i);
    }
    for (int i = 0; i < 12; i++)
    {
        controller->button[i] = SDL_JoystickGetButton(joystick, i);
    }
    controller->hat = SDL_JoystickGetHat(joystick, 0);
}

Re: segfault error; help please?

Posted: Sun Jan 11, 2009 7:28 am
by Amarant
The 'controller' pointer has probably not been initialized.
But to sidestep that problem you could just have this:

Code: Select all

class inputClass
{
    private:
        SDL_Joystick* joystick;
        myController controller; // value instead of pointer
    public:
        inputClass();
        ~inputClass();
        void updateStates();
        myController* getStates();
};
and this

Code: Select all

void inputClass::updateStates()
{
    for(int i = 0; i < 4; i++)
    {
        controller.axis[i] = SDL_JoystickGetAxis(joystick, i);
    }
    for (int i = 0; i < 12; i++)
    {
        controller.button[i] = SDL_JoystickGetButton(joystick, i);
    }
    controller.hat = SDL_JoystickGetHat(joystick, 0);
}
and then implement getStates like this:

Code: Select all

myController * inputClass::getStates()
{
    return &controller;
}
Keep in mind that the pointer that is returned by this implementation of getStates is only valid as long as the instance of inputClass still exists.

Re: segfault error; help please?

Posted: Sun Jan 11, 2009 1:11 pm
by rolland
Thank you for pointing that out. After thinking about what you said, and some scroogling, I've implemented an initializer list. (doing so for a derived class of a similar set-up was a pain)

Code: Select all

inputClass::inputClass() : controller(new myController)
{
    SDL_Init(SDL_INIT_JOYSTICK);
    joystick = SDL_JoystickOpen(0);
    //std::cout << "joystick open" << std::endl;
    updateStates();
}