SDL_BlitSurface分段故障

时间:2011-02-08 14:19:58

标签: c++ sdl segmentation-fault

我在C ++中从SDL_BlitSurface收到分段错误。

这是代码

mainScreen->draw( 0, 0, background, NULL );

(其中mainScreen是Screen类的一个实例),Screen类的draw函数实现为

void Screen::draw( float x, float y, Texture* source, SDL_Rect* clip)
{
    SDL_Rect offset;
    offset.x = x;
    offset.y = y;

    if ( source->myimage == NULL ) throw 5;
    if ( this->screen == NULL ) throw 6;

    SDL_BlitSurface( source->myimage, NULL, this->screen, &offset );
}

和Texture的定义如下:

class Texture
{
    public:
    Texture(std::string imagepath);
    ~Texture();

    private:
    SDL_Surface* myimage;
    float width;
    float height;

    friend class Screen;
    //friend void Screen::draw( float x, float y, Texture source, SDL_Rect* clip);
};

并实施

#include "Texture.h"

Texture::Texture(std::string filepath)
{
    // Initialize the image to NULL to avoid any pointer issues
    myimage = NULL;

    // OPTIMIZED FOR PNGs
    SDL_Surface* loadedImage = NULL;
    SDL_Surface* optimizedImage = NULL;

    loadedImage = IMG_Load( filepath.c_str() );
    if ( loadedImage != NULL )
    {
        optimizedImage = SDL_DisplayFormatAlpha( loadedImage ); // Notice no colour keying (use transparent PNGs)
    }

    myimage = optimizedImage;
    SDL_FreeSurface( loadedImage );
    SDL_FreeSurface( optimizedImage );

    if (myimage == NULL)
    {
        // Some kind of error
        throw 4;
    }

}

Texture::~Texture()
{
    SDL_FreeSurface( myimage );
}

我已经逐步完成了将图像加载到Texture类的区域,这似乎工作正常。 另外,我知道this->screen已正确加载,因为我在单独的函数中使用SDL_FillRect。

1 个答案:

答案 0 :(得分:2)

不要这样做:

SDL_FreeSurface( optimizedImage );

你没有完成表面(它被分配给myimage)。