我找不到这个函数(SDL/OpenGL)的内存泄漏

I cant find the memory leak in this function (SDL/OpenGL)

本文关键字:OpenGL 内存 泄漏 SDL 找不到 函数      更新时间:2023-10-16

那么这个函数:

Texture::Texture(std::string text,TTF_Font * font,int w,int h,int ox,int oy,Uint8 r,Uint8 g,Uint8 b,bool middle)
{
    SDL_Color textColor = {r,g,b};
    SDL_Surface * textSurface = TTF_RenderText_Solid(font,text.c_str(),textColor);
    textSurface = SDL_ConvertSurface(textSurface,sample->format,0);
    float surfAspectRatio = textSurface->w / textSurface->h;
    float texAspectRatio = w / h;
    if(texAspectRatio > surfAspectRatio)//space is to wide so orient to hieight
    {
        if(middle)
        {
            texCoords = new HitBox(-h * surfAspectRatio / 2,-h / 2,h * surfAspectRatio,h,ox,oy,0);
        }
        else
        {
            texCoords = new HitBox(-.1,-.1,h * surfAspectRatio,h,ox,oy,0);
        }
    }
    else//to tall
    {
        if(middle)
        {
            texCoords = new HitBox(-w / 2,-w * (1 / surfAspectRatio) / 2,w,w * (1 / surfAspectRatio),ox,oy,0);
        }
        else
        {
            texCoords = new HitBox(-.1,-.1,w,w * (1 / surfAspectRatio),ox,oy,0);
        }
    }
    glEnable(GL_TEXTURE_2D);
    texData = NULL;
    texData = new Picture();
    glGenTextures(1,&texData->texID);
    glBindTexture(GL_TEXTURE_2D,texData->texID);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, textSurface->w,
                 textSurface->h, 0, GL_RGBA, GL_UNSIGNED_BYTE,
                 textSurface->pixels);
    glBindTexture(GL_TEXTURE_2D,NULL);
    SDL_FreeSurface(textSurface);
    texData->fileName = "text";
}

接受字符串并使用SDL_ttf来呈现文本。然后中间的if else会做一些计算来找到新纹理的位置和大小。我不认为问题出在这里。然后,最后一部分将SDL_Surface转换为开放的GL纹理。

这是纹理类的样子。

class Texture
{
public:
    Picture * texData;
    HitBox * texCoords;
    Texture(int,int,int,int,int,std::string,int,int);
    Texture(std::string,TTF_Font *,int,int,int,int,Uint8,Uint8,Uint8,bool);
    Texture(const Texture *);
    ~Texture();
    void render_tex();
};

我知道内存泄漏是在这个函数中,与析构函数中的问题没有任何关系,因为当我使用另一个构造函数时没有内存泄漏。

我认为内存泄漏大约是3kb,尽管这是一个非常粗略的估计。
SDL_Surface * textSurface = TTF_RenderText_Solid(font,text.c_str(),textColor);
textSurface = SDL_ConvertSurface(textSurface,sample->format,0);

我猜泄漏是在上面复制的第二行。

从文档SDL_ConvertSurface创建一个新的表面。所以你正在泄漏与TTF_RenderTextSolid函数创建的SDL_Surface,因为你使用相同的指针来存储第一个和第二个表面。