我想在屏幕上打印健康信息,以便使用SDL TTF打印游戏,但我会得到内存泄漏。
游戏开始并工作了一段时间(带有文本和所有内容(,但是几秒钟后,它停止了。
通常,在运行SDL_RenderCopy后,您应该释放Textsurface,但即使这样做之后,它仍然行不通。
(我已经测试了代码的其余部分,发现我只在使用RenderHealth后才获得内存泄漏,因此IM 100%确定这会导致问题。(
sdltext.h:
class SDLText {
SDL_Surface* textSurface;
SDL_Texture* text;
TTF_Font * font;
...
}
sdltext.cpp:
void SDLText::renderHealth( int health) {
font = TTF_OpenFont("fonts/OpenSans-Regular.ttf", 80);
if (font == NULL) {
printf("font error");
}
std::string score_text = "health: " + std::to_string(health);
SDL_Color textColor = {255, 255, 255, 0};
textSurface = TTF_RenderText_Solid(font, score_text.c_str(), textColor);
text = SDL_CreateTextureFromSurface(gRenderer, textSurface);
SDL_Rect Message_rect; //create a rect
Message_rect.x = 120; //controls the rect's x coordinate
Message_rect.y = 5; // controls the rect's y coordinte
Message_rect.w = 100; // controls the width of the rect
Message_rect.h = 20; // controls the height of the rect
SDL_RenderCopy(gRenderer, text, NULL, &Message_rect);
SDL_FreeSurface(textSurface);
SDL_DestroyTexture(text);
}
有人可以告诉我我看不到/失踪吗?
解决方案: 最终添加TTF_CloseFont(font);
后,我的问题解决了。
字体已打开,但从未关闭。使用ttf_closefont释放font
使用的内存。
此外,您应该考虑每次渲染时都避免每种字体打开字体。