Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory usage doesn't decrease upon calling free

I have a WebSocket Server using C that will run as a background process on Windows. And this process will accept requests that contains large image data (base64 format).

Everytime a request is received, memory is allocated using malloc. And free'd after the request is executed.

But when I check the Task Manager, the memory usage is not decreased. Also, when I send another request, additional memory is allocated.

My question is, why didn't the process released the allocated memory or reused the previously allocated memory?

like image 658
Ronnie Avatar asked Oct 27 '25 06:10

Ronnie


1 Answers

The underlying implementation of free differs on different platforms, but what you are witnessing is most likely due to lazy memory allocation/deallocation. Your OS (or memory management routines) are aware of the memory that you just freed, but since it is likely that your program is going to request more memory again, it doesn't bother making that memory available to other processes until other processes request it. Hence, the task manager shows that your program's memory usage does not decrease, despite calls to free.

If your program frees and then requests more memory, the underlying memory management routines don't have to give you back the same memory that you freed. Combining free blocks is called coalescing, and is an expensive operation, so it will be delayed to the last moment, and not done at all if possible.

To prove this, you can spin up another program, and have it request a large amount of memory - if your original program properly freed the memory, its memory usage will go down as soon as the new program requests memory.

like image 119
vasia Avatar answered Oct 29 '25 20:10

vasia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!