Search code examples
c++xcodememory-leakssdlinstruments

Has SDL2 a memory leak?


I noticed that all of my projects that use SDL2 have memory leaks, so I have written a little test program that looks like this:

SDL_Init(SDL_INIT_VIDEO);
SDL_Window *win = SDL_CreateWindow("", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 100, 100, SDL_WINDOW_RESIZABLE);
SDL_Renderer *ren = SDL_CreateRenderer(win, 0, 0);

bool running = true;
SDL_Event event;
while (running) {
    while(SDL_PollEvent(&event) != 0) {
        if(event.type == SDL_QUIT) {
            running = false;
        }
    }

    SDL_RenderClear(ren);
    SDL_RenderPresent(ren); //Thanks to keltar 
}
SDL_DestroyRenderer(ren);
SDL_DestroyWindow(win);
SDL_Quit();

I haven't noticed anything that could produce a leak here.

I'm using Instruments, from Xcode, to detect the leaks. The first ten seconds there are no leaks. In the next ten seconds about 15 leaks are created. This will continue less intense up to 40 seconds after the program has started. From 40 seconds on no new leaks are created, but the allocated memory still grows constantly. Edit: The memory no longer grows, when I use SDL_RenderPresent.

So has SDL2 a memory leak, did I make a mistake in the code or is Instruments creating some false positives?


Solution

  • It's possible some mistake where you didn't remove a certain object, or you are re-creating it in a loop. SDL2 itself shouldn't have any memory leaks. However, I highly recommend you to use the freshest version (2.0.10 on this moment is). Please try to draw something in your demo program to verify here is no any memory leaks. Try to repeat a small part of your project's code to render similar. This code doesn't anything and can't reproduce your issue. However, if you have found here is a real memory leak on SDL2 side, please submit a report here https://bugzilla.libsdl.org/. Before that, please pull most fresh sources from official Mercurial repository https://hg.libsdl.org/SDL/ and retry your test to confirm that bug is still presented in the mainstream.