2011-02-08 73 views
0

我在C++中遇到了SDL_BlitSurface的分段错误。SDL_BlitSurface分段错误

这里的代码

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

(其中mainScreen是Screen类的一个实例)和Screen类的绘制函数被实现为

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); 
} 

和纹理被定义为如下:

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。

+0

发布一个完整的,最小的示例来演示问题。 – genpfault 2011-02-08 16:23:07

回答

2

不要这样做:

SDL_FreeSurface(optimizedImage); 

你是不是在表面做了(它被分配到MYIMAGE)。