SDL_TTF closefont() fail when using with SDL_Quit event

I’m using VS 2022 and C++. So, I’m making a game involving SDL and SDL_TTF. After everything, I free the font and quit like this:


The upr. closefont immplementation is just { TTF_Closefont(font); return this} so I can chain call. Unfortunately, this gives me a memory leak. I found the solution to this by putting all the mess below the event loop just before quitting.
Magically, the memory leak went away. Can anyone give me an explanation? Thanks!

Are you sure this is where you “quit” the loop? If the loop variable is set to false somewhere else, and the calls to closefont never get executed, that would explain it.

Are you sure none of the fonts are used after this? (Note that whatever code that comes after the switch statement inside the loop will still get executed one more time)

Yeah, it sounds like this isn’t the only place exiting your game loop.

It would be better to just set the quit flag in the switch statement, and then do all your cleanup after the loop.

The error is random. Sometimes it works, sometimes it yields. This is the only place where I quit the loop, indeed. Also, I put an std::cout statement right before the closefont and it still prints every time. By the way, this question only comes out from my curiosity. I solved the problem already.

Sounds like some type of UB. It’s difficult for us to say what goes wrong without a complete program that reproduces the error to look at.

Not at all sure it’s related to your problem, but you really should check the return value of SDL_PollEvent before using the event object.

Instead of this:

SDL_PollEvent(&ev);
switch (ev.type) {
    ...
}

Do this:

while (SDL_PollEvent(&ev)) {
    switch (ev.type) {
        ...
    }
}

You could use if instead of while but normally while is the right choice because we want to handle all events without delay. You cannot just copy paste your original code into this loop because you might get multiple SDL_QUIT events which would try to close the same fonts twice, unless you make sure to break out of the event loop when it happens, but you still need to make sure to avoid using the fonts in the rest of your game loop, so putting the clean-up code at the end is still a good idea (that way it’s much easier to get right).