Search code examples
crenderingsdlsdl-2sdl-ttf

SDL memory leak


So I tryed to make something on SDL, but on first programm I have memory lear (idk leak or not) so there is some code:

#include <stdio.h>
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
#define SCREENSIZEX 180
#define SCREENSIZEY 300
SDL_Window* mainwind = NULL;
SDL_Renderer* rend = NULL;
TTF_Font* Usefont = NULL;

int main(int argc, char* argv[])
{
    SDL_Init(SDL_INIT_EVERYTHING);
    Uint32 windowflags;
    windowflags = SDL_WINDOW_SHOWN;
    mainwind = SDL_CreateWindow("FooBar", 
                                SDL_WINDOWPOS_CENTERED, 
                                SDL_WINDOWPOS_CENTERED, 
                                SCREENSIZEX, 
                                SCREENSIZEY, 
                                windowflags);
    rend = SDL_CreateRenderer(mainwind, -1, SDL_RENDERER_ACCELERATED);
    SDL_SetRenderDrawColor(rend, 255, 255, 255, 255);
    int imgFlags = IMG_INIT_PNG;
    IMG_Init(imgFlags);
    TTF_Init();
    Usefont = TTF_OpenFont("DOTMBold.TTF",90);

    SDL_Surface* TextSurf = NULL;
    SDL_Texture* TextTexture = NULL;

    SDL_Color UsingColor;
    UsingColor.r=0;
    UsingColor.g=255;
    UsingColor.b=255;
    UsingColor.a=100;

    bool exit = false;
    char Text[500];
    int counter = 0;
    SDL_Event evneet;
    while(!exit)
    {
        SDL_PollEvent(&evneet);
        SDL_RenderClear(rend);
        counter++;
        TextSurf = TTF_RenderUTF8_Blended(Usefont, Text, UsingColor);
        TextTexture = SDL_CreateTextureFromSurface(rend, TextSurf);
        SDL_FreeSurface(TextSurf);
        TextSurf = NULL;
        SDL_RenderCopy(rend, TextTexture, NULL, NULL);
        TextTexture = NULL;
        SDL_DestroyTexture(TextTexture);
        SDL_RenderPresent(rend);
    }
    SDL_FreeSurface(TextSurf);
    TextSurf = NULL;
    SDL_DestroyTexture(TextTexture);
    SDL_DestroyRenderer(rend);
    SDL_DestroyWindow(mainwind);
    SDL_Quit();
    return 0;   
}

Problem: some screenshots

Idk how to fix this and tryed to do a lot of freeing and memory manipulations. This programm do only one task. Just counting frames (in code only 0 displayed) Its 3rd my try to make rendering and always i got the same. Please help!


Solution

  • The answer was strange. Thanks Ctx thats first part of this big mess with rerenderring surfaces and textuers. As for me big mistake was NULLing texture when i need to pass "nullptr".

    SDL_FreeSurface(AlreadyDrawedAndUsedOnSurface);
    AlreadyDrawedAndUsedOnSurface = NULL;    //BAD!
    AlreadyDrawedAndUsedOnSurface = nullptr; //good)
    

    Very strange for me but it works!