Should I free all allocated memory when I finish a program?


It is commonly accepted that when I allocate a block of memory I am responsible for freeing it. This is particularly true when programming based on RAII. However the following program works perfectly:

int main() {
    int* ptr = new int[99999];
    return 0;

Here the system must be able to release everything that the process has allocated.

What is considered good practice here? Should I always free the memory I allocate? Are there any problems/advantages in letting this work for the system?


One point to keep in mind is that code that is now a complete program can eventually be refactored to become a feature of another, larger program. If the original program didn't care about freeing resources (because the OS would do it for it), now it will start leaking the program bigger every time its functionality runs. Many hours of debugging will be wasted on identifying the source of the problem, let alone refactoring the original code to behave right.

Scroll to Top