Strange issue/bug (SDL_ClearRenderer or SDL_LoadTexture)


Here is this code, when you run it, you will see the background image. After a short period of time (about 15-20 seconds), the blackground image disappears, and the window becomes black. I found a workaround, you just have to take out: “background = IMG_LoadTexture(renderer, “…/images/background.png”);” from the do-while loop, and put before it. But i still dont understand why this issue occourd. Can someone explain me please?

int main(int argc, char** argv)
    SDL_Renderer* renderer;
    SDL_Window* window;

    window = SDL_CreateWindow("Test - SDL 2.0", 100, 100, 800, 600, SDL_WINDOW_SHOWN);
    renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

    SDL_Texture *background = NULL;
    SDL_Rect background_rect;

    SDL_Event ev;
    bool quit = false;

        background = IMG_LoadTexture(renderer, "../images/background.png");
        while(SDL_PollEvent(&ev) != 0)
            if(ev.type == SDL_KEYDOWN) quit = true;
            else quit = false;
       for(int i=0; i<50; i++)
        SDL_Texture* combined_image = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, 96, 120);
        SDL_SetTextureBlendMode(combined_image, SDL_BLENDMODE_BLEND);
        SDL_SetRenderTarget(renderer, combined_image);
        SDL_SetRenderTarget(renderer, NULL);
        SDL_RenderCopy(renderer, background, NULL, &background_rect);

Your program probably crashes/freezes because it runs out of memory. What you’re doing in your code at this moment is actually re-creating an SDL_Texture over and over, every frame: background = IMG_LoadTexture(renderer, "../images/background.png"), which will fill up the memory until it runs out, since you’re not destroying it at the end of the loop.
The same thing occurs with your ‘combined_image’ texture, which you’re also re-creating every frame, with the difference that you’re re-creating it 50 times(!) every frame, without destroying it/them in the end of the loop.

You really should create your textures in the startup/initialization of your program, i.e before the main loop starts, then render the textures in the main loop and in the end of the program, before it shuts down, destroy the textures.

1 Like

I try that, thanks a lot Naith.