C++ delete does not free all memory (Windows)

I’m sure this is a duplicate, but I’ll answer it anyway:

If you are viewing Task Manager size, it will give you the size of the process. If there is no “pressure” (your system has plenty of memory available, and no process is being starved), it makes no sense to reduce a process’ virtual memory usage – it’s not unusual for a process to grow, shrink, grow, shrink in a cyclical pattern as it allocates when it processes data and then releases the data used in one processing cycle, allocating memory for the next cycle, then freeing it again. If the OS were to “regain” those pages of memory, only to need to give them back to your process again, that would be a waste of processing power (assigning and unassigning pages to a particular process isn’t entirely trivial, especially if you can’t know for sure who those pages belonged to in the first place, since they need to be “cleaned” [filled with zero or some other constant to ensure the “new owner” can’t use the memory for “fishing for old data”, such as finding my password stored in the memory]).

Even if the pages are still remaining in the ownership of this process, but not being used, the actual RAM can be used by another process. So it’s not a big deal if the pages haven’t been released for some time.

Further, in debug mode, the C++ runtime will store “this memory has been deleted” in all memory that goes through delete. This is to help identify “use after free”. So, if your application is running in debug mode, then don’t expect any freed memory to be released EVER. It will get reused tho’. So if you run your code three times over, it won’t grow to three times the size.

Leave a Comment