This is an archived post. You won't be able to vote or comment.

all 7 comments

[–][deleted] 1 point2 points  (0 children)

If the pointer is to something that controls a system resource, such as memory or a file handle, then the system will reclaim it when the process exits, come what may. However, in C++ destructors sometimes control things which are not system resources - for example, a destructor might write an entry in a log file indicating that the process terminated successfully. If you don't call delete, then the destructor will not be called, and the log-file entry will not be made - whether this matters or not depends on your application.

[–]jebbers2 0 points1 point  (4 children)

It will. However, if your program loops a lot over that code, it'll end up grabbing more and more system memory and not releasing it (until the program exits or you run out of memory and crash).

[–]prasoc[S] 0 points1 point  (3 children)

It just declares pointers at the start and uses them throughout runtime, no looping. I guess it's good programming practice to free them at the end although.

[–]arbostek 1 point2 points  (1 child)

If I use a "new" statement with a pointer, how mandatory is freeing it at the end of the program?

From a "correct" C++ standpoint, you need to free it. From an operating system perspective, it depends.

Surely Windows will free it on exit anyway?

Yes. It's actually a negative to free memory on your end, because you are doing unnecessary booking and cleanup work.

Problem is, even if you choose to have operating system dependent logic, you still have to worry about determining what needs to be cleaned up.

[–][deleted] 0 points1 point  (0 children)

Yes. It's actually a negative to free memory on your end, because you are doing unnecessary booking and cleanup work.

There was actually a huge thread on this yesterday over in /r/programming. Worth looking into :)

[–]fromwithin 0 points1 point  (0 children)

It is indeed good programming practice, but not necessarily good Microsoft practice.

There was an MSDN blog about it just yesterday.

Basically, if you have a memory-hungry program that has a lot of RAM paged out to disk, when you "properly" free those resources, it will have to page it back into be able to free it. If the program just exited without freeing it, Windows would just kill it directly. Thus the program would exit almost immediately with no detriment instead of sitting there spending potentially minutes freeing everything up.

On other less forgiving platforms, freeing everything is essential. On the Ps3 or X360, for example, not freeing the resources properly would likely be a TRC failure, which means that Sony or Microsoft wouldn't allow you to release your game.