【问题标题】:Modifying pointer leads to SIGSEGV signal修改指针导致 SIGSEGV 信号
【发布时间】:2013-11-27 15:07:56
【问题描述】:

这是我的第一次体验,所以不要挑剔。
这是 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();

};

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

activity::activity()
{

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

请帮我看看... 谢谢

【问题讨论】:

  • 您将主事件循环放在构造函数中并从中显式调用析构函数?太丑了你想做什么?
  • 这是一个肯定会被清理的原始代码,我正在创建一个演示图形应用程序以满足学习需求
  • 按照现在的设置,在主事件循环结束之前,activity 的构造函数体永远不会被调用。
  • 哦,非常感谢。没错,就是问题所在。

标签: c++ class pointers sdl segmentation-fault


【解决方案1】:

问题是双重的:

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

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

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

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

【讨论】:

  • 好的,我把它收起来。我刚开始开发这个,我还在努力让它工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-22
  • 1970-01-01
相关资源
最近更新 更多