Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Freeing dynamically allocated memory

In C++, when you make a new variable on the heap like this:

int* a = new int;

you can tell C++ to reclaim the memory by using delete like this:

delete a;

However, when your program closes, does it automatically free the memory that was allocated with new?

like image 565
Zerg Avatar asked Jul 18 '10 16:07

Zerg


1 Answers

Yes, it is automatically reclaimed, but if you intend to write a huge program that makes use of the heap extensively and not call delete anywhere, you are bound to run out of heap memory quickly, which will crash your program.

Therefore, it is a must to carefully manage your memory and free dynamically allocated data with a matching delete for every new (or delete [] if using new []), as soon as you no longer require the said variable.

like image 167
Kristian D'Amato Avatar answered Oct 05 '22 03:10

Kristian D'Amato