c++ - SDL_TTF 绘图 int 到字符串内存泄漏?

标签 c++ memory-leaks drawing sdl sdl-ttf

好吧,我一直在尝试显示一个能够更新并反射(reflect)在屏幕上的整数。 (例如显示鼠标位置的 x 和 y 坐标),它按照我想要的方式运行,但后来我打开了很好的 ol'task 管理器,运行 7 分钟后发现我已经达到了大约 600mb。当我注释掉我在屏幕上呈现的整数时(这样它们就不会绘制或更新)。该程序在 7 分钟后徘徊在 20mb 左右。我一直没有找到问题所在,谁能帮我找出我哪里出错了?谢谢。

//文本管理器.h

#pragma once
#ifndef TEXTMANAGER_H
#define TEXTMANAGER_H

#include <SDL_ttf.h>
#include "graphicsManager.h"
#include <sstream>

struct textManager{
public:
    textManager(){}
    ~textManager();
    void SetText(std::string msg, int x, int y);
    void draw();
    void setFont(std::string filepath, int size);
    void changeFontSize(int size);
    int getWidth();
    int getHeight();
    void setColor(int r, int g, int b);
    void intToString(Uint32 number, int x, int y);

private:
    TTF_Font*font;
    SDL_Texture*texture;
    SDL_Rect dst;
    SDL_Rect src;
    SDL_Surface*surface;
    SDL_Color color;
    std::stringstream ss;
    std::string text;


};

#endif // TEXTMANAGER_H

//部分TextManager.cpp

    void textManager::intToString(Uint32 number, int x, int y)
{
    ss << number;
    text = ss.str().c_str();
    surface = TTF_RenderText_Blended(font, text.c_str(), color);
    if (surface == NULL)
        cout << "surface is NULL \n" << SDL_GetError() << "\n";
    texture = SDL_CreateTextureFromSurface(Gfx::Instance()->getRenderer(), surface);
    SDL_FreeSurface(surface);
    src.x = 0;
    src.y = 0;
    src.w = dst.w = surface->w;
    src.h = dst.h = surface->h;
    dst.x = x;
    dst.y = y;

    SDL_QueryTexture(texture, NULL, NULL, &src.w, &src.h);
    ss.str(std::string().c_str());

}

void textManager::draw()
{
    SDL_RenderCopy(Gfx::Instance()->getRenderer(), texture, &src, &dst);
}


textManager::~textManager()
{
    if (texture != NULL)
        SDL_DestroyTexture(texture);
    font = NULL;
    surface = NULL;
    ss.clear();
    delete surface;
}

最佳答案

每次您调用 textManager::intToString 时,您都会使用 TTF_RenderText_Blended 创建一个表面,然后从该表面创建一个纹理。

您正在释放表面,但看起来您没有对纹理做同样的事情。这意味着纹理点的每一帧都将被重新分配,但内存不会被释放,从而导致持续的内存泄漏。

关于c++ - SDL_TTF 绘图 int 到字符串内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27879014/

相关文章:

docker - Nifi 1.6.0内存泄漏

php - 沿路径绘制平行线 - PHP GD

ios - 完全删除 UIBezierPath 和 CAShapeLayer 绘制的项目

c++ - 将 TI 链接器命令文件与 Clang 结合使用

c++ - 没有匹配函数调用 'Book::Book()'

c++ - cpp - valgrind - 大小为 8 的无效读取

python - 使用 pygtk 和 glade 将 pixbuf 绘制到绘图区域

C++ 如何将 std::mutex 和 std::lock_guard 与仿函数一起使用?

c++ - 如何以图形方式显示 .map 文件中的内存布局?

c - Valgrind 内存泄漏这是什么错误?