FreeSurface() simple crash on MSVC++17

Hey guys, having some trouble with a little interesting bug pertaining to FreeSurface().

	SDL_Texture* t = NULL;
	SDL_Surface* s = IMG_Load("assets/textures/alch.png");
	if (s != NULL)
	{
		t = SDL_CreateTextureFromSurface(r, s);
		SDL_FreeSurface(s);
	}

For some reason this is causing an exception in SDL_malloc.c (SDL_free(), line 5432, specifically on (void)SDL_AtomicDecRef(&s_mem.num_allocations);}).

I’m a decently seasoned C++ developer and I feel like I’m going a little crazy trying to figure this out. I’ve tried using both SDL2 libraries from VCPKG and the SDL2 website. No multi-threading or anything crazy. Just these few lines of code after SDL_Init(SDL_INIT_EVERYTHING).

Anyone have any ideas?

Have you checked what SDL_CreateTextureFromSurface is returning? And if it’s NULL called SDL_GetError() ?

https://wiki.libsdl.org/SDL_CreateTextureFromSurface

Thanks for the reply! The texture it not NULL and I’m not getting anything out of SDL_Error.

The texture draws properly.

This definitely looks broken - no matter if creating the texture failed or not, freeing the surface afterwards shouldn’t crash

I’m at work now but I’m leaving soon.

When I get home I’ll dig in to it a bit more. IIRC it seemed like num_allocations wasn’t getting incremented properly. But I don’t know enough about the inner workings of SDL2 to know if that’s actually the issue.

s_mem.free_func(ptr);
(void)SDL_AtomicDecRef(&s_mem.num_allocations);

So it looks like it’s these two functions in SDL_Free. This is the contents of the SDL_PixelFormat* before being sent to the SDL_Free function…

https://imgur.com/a/PvbdctZ

Is it possible that it’s how SDL_Image is loading in the surface?

can you tell us more about the exception itself?
what kind of exception is it, what exactly does it say? what’s the backtrace?

MSVS isn’t giving me any more information other than

“Exception Thrown
TestBench.exe has triggered a breakpoint”.

I’m doing the free from my main function so the callstack goes straight in to SDL2 library code.

HI Just wondering if you got to the bottom of this? I’m having the exact same issue, my image displays fine if I don’t free the surface, but as soon as I put that line back in it crashes.

Only difference I’m using GDB and Mingw. It’s reporting “Exception has occurred”. It’s in SDL_malloc.c line 5432. Using SDL 2.0.16.