Shanpei Zhou
Shanpei Zhou

Reputation: 391

Dynamically allocated memory has to be deleted in C++?

Say I have a list<TreeNode> in my program. Every time I use new to dynamically allocate a TreeNode class and attach it to the list; when the program is over, the list is gone. However, I am not sure if all those elements attached to it will be deleted automatically as the list is gone. Do I still need to go through the list and delete all elements myself?

Also, what damage will be caused by a memory leak? When a process is over, its memory space will be released I think, so nothing is actually left behind that harms my computer.

Upvotes: 0

Views: 197

Answers (3)

C. K. Young
C. K. Young

Reputation: 222973

If the only thing your TreeNode occupies is memory, you don't need to release them when exiting your program. However, if it contains, say, a buffered writing file stream, and you don't release that, there may be data still remaining in the buffer that won't get written to disk. And then you will have data loss. :-)

P.S. I need to add, this strategy of letting the OS free everything for you only applies if your program is short-lived, and you have no "trash" objects (i.e., you need to retain references to all created objects for the program's lifetime). If it's long-lived (but you have no trash objects), just use static memory, and don't do any dynamic allocation. If you have trash objects, you need to free them. No questions asked. :-)

Upvotes: 1

PaulMcKenzie
PaulMcKenzie

Reputation: 35440

Right now, your list<TreeNode> destroys itself because the program has terminated, but now let's say you are in a situation where you are using local list<TreeNode> objects that are created and destroyed in a loop or something similar. That memory leak now turns into something you do have to worry about.

Bottom line is your code shouldn't leak, regardless of the situation. The only exception maybe singleton or similar patterns, where there may be some justification for letting the object "die without cleanup". But for something like a list class, absolutely no leaks should be present.

In addition, what if the process is not supposed to shut down? What if it is a mission critical app that must run 24 hours, every day? That leak now turns into a disaster -- it is you or that (now angry) coworker who will get that phone call in the middle of the night trying to restart the system due to the resources being exhausted.

Upvotes: 2

Aesthete
Aesthete

Reputation: 18850

If you've used new to allocate a TreeNode object everytime you add it to the list, you're going to have to delete that object as well before your list is cleared.

One new = one delete

Upvotes: 0

Related Questions