c++ - SDL_BlitSurface 分割错误

标签 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。

最佳答案

不要这样做:

SDL_FreeSurface( optimizedImage );

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

关于c++ - SDL_BlitSurface 分割错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4934159/

相关文章:

c++ - 这个程序会不会导致内存泄漏

c++ - 直接用rapidjson保存json到文件

c++ - TTF_RenderText_Solid 使我的 ram 增加到 2GB 并返回 NULL

c++ - 段错误 : "...no such file or directory"

c - 段错误(核心转储)字符数组

c++ - IBM AIX std::clock()?

C++ 问题 :After assigning value to a variable, 另一个变量改变了

c++ - 如何连接一个字符串和一个整数来生成文件名?

c - 这段代码中的音频是如何播放的(C/SDL)

c - 用 C 读取文件时出现段错误