Question

I have some large memory allocations in my program, and I need most of it throughout the program. So what is the best place to delete this memory? I really would not want to leave it alone.. so is WM_DESTROY message always sent? I mean even though my application is killed by some other process..? If not please guide which is the best place to delete the memory.

Was it helpful?

Solution

If an application is killed (via TerminateProcess), your code doesn't run, so there's literally nothing you can put in your code to "clean up" things.

If an application is merely quitting after receiving WM_QUIT, then eventually the message loop will exit and the main (or WinMain) function will return - thus your application-wide cleanup should be at the end of main/WinMain, as long as body of code within main/WinMain doesn't prematurely explicitly return. To assure of this, you could move the body of WinMain (or main) into a separate function, and invoke that from the actual main function, then do the cleanup, and finally return.

You're correct that the per-window cleanup should be done upon receiving WM_DESTROY, but this will only happen if the window or the application was cleanly closed/quit, not terminated.

You can also use the unhandled exception filter, but this is problematic since there are no guarantees that the unhandled exception wasn't thrown due to memory corruption. There's little point to "freeing" memory when there's memory corruption already, you could, for example, end up in an endless loop.

In other words, what you're attempting to do is best described as Cargo Cult Programming. You seem to believe that there is some magic incantation that, if you just do it, will somehow protect you from "evil". Said incantation is a fantasy, a figment of your imagination. There's no code for it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top