olekolek1000
olekolek1000

Reputation: 23

SDL2 C++ - SDL_FreeSurface does not remove the image from RAM

I have a problem with memory leak. RAM usage in my application does not decrease after SDL_FreeSurface function.

Code:

//10 000 KB RAM
SDL_Surface * surface = SDL_CreateRGBSurface(NULL,32000,5400,1,0,0,0,0);
//700 000 KB RAM
SDL_FreeSurface(surface);
//700 000 KB RAM

Why RAM usage does not decrease?

free(surface);
delete surface;
surface->pixels=NULL;

also they do not work.

Upvotes: 2

Views: 751

Answers (1)

user1641854
user1641854

Reputation:

Because it is a way memory allocator works. free'ing or delete'ing memory from code doesn't definitely means that your user space memory allocator will be eligible to return allocated memory to the OS. The reason is that it can have some optimization policies. Imagine that you continuously malloc(3) 100 MB of memory and the free(3) it. The overhead of returning and getting back memory from OS will be huge. Rather userspace memory allocators do some optimization on lifetime of allocated memory blocks. So, you don't need to consider every malloc(3), new, free(3) or delete as a function call, that will result in changes of RSS of your process. Consider it as a smart abstraction over the memory you get from OS. And if you really want to check you program against memory leaks - consider to use specific tools - e.g. valgrind.

Also, this code:

free(surface);
delete surface;

is definitely wrong. You have to use a deallocator for memory block corresponding to allocator, that you used to allocate memory. malloc/free, new/delete. Both or non matching pair is an error.

Upvotes: 2

Related Questions