简体   繁体   中英

C++ SDL2 memory leak? SDL_RenderClear?

I'm using SDL2 on Windows with Code::blocks.

I write this little program. But it cause a memory leak! The code is very simple. it does only clear and update the screen.

#include <SDL.h>



const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;

SDL_Window* window = NULL;
SDL_Renderer* renderer = NULL;
SDL_Event event;
bool quit = false;

void loadSDL();
void closeSDL();



int main( int argc, char* args[] )
{
    loadSDL();

    while(!quit)
    {
        while(SDL_PollEvent(&event) != 0)
        {
            if(event.type == SDL_QUIT)
            {
                quit = true;
            }
        }

        SDL_RenderClear( renderer );
        SDL_RenderPresent( renderer );
    }

    closeSDL();
    return 0;
}

void loadSDL()
{
    SDL_Init( SDL_INIT_VIDEO );
    window = SDL_CreateWindow( "Test1", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
    renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
    SDL_SetRenderDrawColor(renderer, 0x0, 0x0, 0x0, 0xFF);
}

void closeSDL()
{
    SDL_DestroyRenderer( renderer );
    SDL_DestroyWindow( window );
    window = NULL;
    renderer = NULL;
    SDL_Quit();
}

I don't know what is wrong...

If I comment this line out

SDL_RenderClear( renderer );

There is no memory leak!

Memory leaks are not the most obvious things to track down. To properly identify a leak, you'll need to use a profiling tool as mentioned in the comments.

The most common reason for what you are seeing is that the OS is free to assign memory to processes before they request it and to delay releasing unused memory. Sometimes this looks like a leak as your process's RAM usage grows in Task Manager. If you wait for a while, it will likely stabilize.

As for a leak specifically in SDL_RenderClear(), it helps to know which renderer you're using. They have different code paths. However, in this case they are quite similar. Here's the GL version from SDL_render_gl.c:

static int
GL_RenderClear(SDL_Renderer * renderer)
{
    GL_RenderData *data = (GL_RenderData *) renderer->driverdata;

    GL_ActivateRenderer(renderer);

    data->glClearColor((GLfloat) renderer->r * inv255f,
                       (GLfloat) renderer->g * inv255f,
                       (GLfloat) renderer->b * inv255f,
                       (GLfloat) renderer->a * inv255f);

    data->glClear(GL_COLOR_BUFFER_BIT);

    return 0;
}

The only indirect call here is GL_ActivateRenderer(), which does a simple comparison and set. The Direct3D RenderClear() is a little more complicated but does essentially the same thing. It is unlikely that your problem is here.

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