SDL内存泄漏

时间:2018-07-01 20:50:19

标签: c rendering sdl sdl-2 sdl-ttf

所以我试图在SDL上做一些事情,但是在第一个程序上我有内存空间(是否存在IDK泄漏),所以有一些代码:

#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;   
}

问题: some screenshots

Idk如何解决此问题,并尝试执行许多释放和内存操作。 该程序仅执行一项任务。仅计数帧(在代码中仅显示0) 这是我进行渲染的第三次尝试,但我总是得到相同的结果。 请帮忙!

2 个答案:

答案 0 :(得分:6)

这看起来很可疑:

while(!exit)
{
    ...
    TextTexture = SDL_CreateTextureFromSurface(rend, TextSurf);
    ...
    TextTexture = NULL;                // A
    SDL_DestroyTexture(TextTexture);   // B
    ...
}

SDL_DestroyTexture()在这里没有有效的句柄,但是传递了NULL指针。您必须交换A和B线,以便可以正确释放纹理。

答案 1 :(得分:0)

答案很奇怪。谢谢Ctx,这是表面和纹理重新渲染的大混乱的第一部分。对于我来说,最大的错误是当我需要传递“ nullptr”时将纹理清空。

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

对我来说很奇怪,但是有效!