What's the purpose of Free up memory Allocated????

What's the purpose of Free up memory Allocated???? In C++ Or C.
Do you mean what is the purpose of freeing up memory allocated on the heap with the use of the new operator?

If that is what you mean, then it is to stop your program leaking memory away while it is running. Your code basically 'borrows' the computers high end memory of which you only have a finite amount available. So it is your responsibility as the programmer to ensure that when you have finished with that memory that you give it back for other programs to use. This might not seem to be a big deal on your computer that may have quite a bit of memory available, but consider if you are responsible for programming a program to operate on a mobile phone that doesn't have too much available memory, the user wouldn't be very happy if they had to constantly re-boot their phone because you hadn't bothered to free up memory when you were done with it would they?

So, if you allocate memory from the heap with the new operator it is imperative that you 'delete' it when you are done with it before your variable (aka pointer) goes out of scope. As soon as you no longer have a variable that has the address of the memory you used you are no longer able to free it up and hand it back to the operating system.

Does that make sense now? If you don't want to bother with correct memory management then don't program in C++. Even if you program in a language that has a garbage collector, i.e. C#, or Objective-C, you should not rely on the garbage collector. If you use a large chunk of memory for a short while due to loading in a photo as an example, you should free up the memory as soon as you are done with it, otherwise it maybe a while before the GC does it for you and your program may end up being very sluggish.
Last edited on
Topic archived. No new replies allowed.