修改指针会导致SIGSEGV信号

时间:2013-11-14 14:38:59

标签: c++ class pointers sdl sigsegv

这是我的第一次经历,所以不要挑剔 这是SIGSEGV问题,它只出现在类链接中。 “SDL_surface * ScreenSurface”指针中的问题。
这里是代码......

屏幕标题

class screen
{
public:
    screen();
    SDLclass_Window *MainWindow=NULL;
    SDL_Surface *ScreenSurface=NULL; //this is the problem pointer to the struct that cause error
    //Those pointer are't NULL, see below
    virtual ~screen();
protected:
private:
    const int SCREEN_WIDTH = 1280;
    const int SCREEN_HEIGHT = 726;
    bool init();
};

屏幕代码

screen::screen()
{

if(!init())
    {
        std::cout<<"ERROR at INIT";
        SDL_Delay( 4000 );
    }
else
    {
    bool quit=0;
    SDL_Event e;
    while (!quit)
        {
        SDL_UpdateWindowSurface(MainWindow);

            //Looking for events
            while( SDL_PollEvent( &e ) != 0 )
            {
                //User requests quit
                if( e.type == SDL_QUIT )
                {
                    quit = true;
                }
            }
        }
    }


this->~screen();
}
bool screen::init() //Initialization
{
    bool succses=1;
    if (SDL_Init( SDL_INIT_VIDEO ) < 0 )
    {
        std::cout<< "SDL could not initialize! SDL_Error:"<< SDL_GetError()<<std::endl;
        succses=0;
        return succses;
    }
    MainWindow= SDL_CreateWindow( "Arachy: WIP Version", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN ); //Setting parameters to SDL_window
    if (MainWindow==NULL)
    {
        std::cout<<"can't create window"<<SDL_GetError()<<std::endl;
        succses=0;
        return succses;
    }
    else
    {
        //Get window surface
        ScreenSurface = SDL_GetWindowSurface( MainWindow );// telling ScreenSurface that it our main screen surface
    }

    return succses;
}

screen::~screen()
{
    SDL_Quit();
}

活动标题 (另一个使用SDL_Surface的类,它在上面的Screen类中定义)

class activity
{
public:
    activity();
    virtual ~activity();
protected:
private:
    screen mainScreen;
    void load();

};

活动代码(我试图在调试期间收到SIGSEGV信号之后用SDL_FillRect()修改SDL_Surface

activity::activity()
{

    SDL_FillRect(mainScreen.ScreenSurface,NULL,SDL_MapRGB(mainScreen.ScreenSurface->format,255,000000,255));
}

请帮我看看...... 谢谢

1 个答案:

答案 0 :(得分:0)

问题有两个:

A) screen的析构函数可能被调用两次,导致SDL_DestroyWindow()和SDL_FreeSurface()在无效的非NULL指针上被调用。

如果你绝对想要两次调用你的析构函数,你至少应该在销毁它们指向的对象后将这些指针重置为NULL。

但在大多数情况下,您应该简单地知道 not 显式调用析构函数...

B)现在设定,在主要事件循环结束之前,永远不会调用activity的构造函数体。

相关问题