简体   繁体   中英

SDL2 Memory Leaks C++

So when I run the app, at the biginning every thing runs smooth, but the more it goes, the slower it is. I looked at the memory it was using and when it reaches 400 mb it completely stops for 30 secs and then drop back to 200.

I am pretty new to SDL2, and I assume it is because each frame I call:

optionsTS = TTF_RenderText_Blended(font, "Options.", blanc);
optionsT = SDL_CreateTextureFromSurface(renderer, optionsTS);

for example and I have plenty of them.

The problem is that I don't know how to delete properly the object each frame, because if I do a SDL_FreeSurface I get an error.

I won't publish my whole code because it's a mess, but if you want it, feel free to ask.

Do you know how to fix that?

Just thought I would turn my comment into an answer.

In your code you call

optionsTS = TTF_RenderText_Blended(font, "Options.", blanc);
optionsT = SDL_CreateTextureFromSurface(renderer, optionsTS);

every frame, I suspect that if you remove them from there, initialise them outwith of the render loop and simply pass them in as arguments, you should lose the memory leak: the reason being that you will create only one in-memory instance of each and then you can repeatedly use them as needed. On looking at it again, I suspect that you could destroy optionTS once you have made optionT , that way you will save even more memory. (not tested yet as my main machine just crashed this weekend, and I am still re-installing drivers and VS2010)

As a general rule, try and not create/destroy any objects in the render loop, tends to get big and messy fast.

Consider taking advantage of RAII in C++ if possible. For example, create a class that wraps an SDL_Surface and calls SDL_FreeSurface in the destructor.

class MySurface
{
public:
    MySurface(SDL_Surface & surface) : m_surface(surface) {}
    ~MySurface() {SDL_FreeSurface(m_surface);}

    SDL_Surface & GetSDLSurface() {return m_surface;}

private:
    SDL_Surface & m_surface;
};

You would then create an instance of MySurface every time you grabbed an SDL_Surface from the SDL API, and you won't have to worry about when or whether to free that surface. The surface will be freed as soon as your instance of MySurface goes out of scope.

I'm certain better implementations can be written and tailored to your needs, but at a minimum something similar to this may prevent you from having leaks in the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM