C – Is Malloc-ed Memory Automatically Freed on Application Exit?

c++memory-management

Let's say I have the following C code:

int main () {
  int *p = malloc(10 * sizeof *p);
  *p = 42;
  return 0;  //Exiting without freeing the allocated memory
}

When I compile and execute that C program, ie after allocating some space in memory, will that memory I allocated be still allocated (ie basically taking up space) after I exit the application and the process terminates?

Best Answer

It depends on the operating system. The majority of modern (and all major) operating systems will free memory not freed by the program when it ends.

Relying on this is bad practice and it is better to free it explicitly. The issue isn't just that your code looks bad. You may decide you want to integrate your small program into a larger, long running one. Then a while later you have to spend hours tracking down memory leaks.
Relying on a feature of an operating system also makes the code less portable.

Related Question