Possible Duplicate:
Is it acceptable not to deallocate memory
This is a general question. I have some c++ desktop proj开发者_Go百科ects that work with some global data structure. My question is, before I exit the applications, do I need to deallocate the memories for these data structures? Anyway, the memory will be destructed by the OS after the app is closed.
Short answer: No. (Yes if you're sufficiently pedantic (which is a good thing)... see edit)
All memory allocated by a program will automatically be freed by the operating system when the program exits.
However, it's good practice to get in the habit of cleaning up after yourself, so you don't forget to do so when it is necessary.
Edit: According to @David Thornley's comment on the question, not all operating systems behave this way. I have no reason not to believe that, but I do believe that any consumer OS you're every likely to encounter does. However, it is always a best practice to never rely on non-standard features, no matter how common, unless you have a specific reason for doing so.
No, you don't have to. It doesn't result in Undefined Behavior as far as C++ is concerned. But it's not a good practice to get used to.
Yes, memory will be reclaimed by the OS, however, it's a good practice to always free any memory you alocate, so that you can check for memory leaks in your program. If you don't, it's harder to spot a leak using a tool like valgrind
As you say, your operating system frees all the memory your program had used when the program terminates, so in principle you don't have to worry about that. One might even argue that the OS does the job faster in one go than you could do it piece by piece.
If you know exactly which global objects you leave dangling at the end, then that's absolutely fine.
It might just be good practice to always write code that terminates completely cleanly to avoid overlooking actual leaks; it just depends on your confidence in your code.
精彩评论