Category: Gyan

NO MEMORY IS LEAKED ONCE PROCESS EXITS

When short lived programs are written, we might allocate some space using malloc() and forget to free it. The programs runs and then successfully completes.

It is actually wrong not to call free() on the allocated bunch of memory. But this will not lead to a memory leak in case we forget to call free(). The reason for this is simple. There are 2 levels of memory management working.

  1. The memory management performed by the OS: This hands out memory to processes as they run and takes it back when they exits.
  2. The memory management performed by the user: This is managed by the user, by explicitly calling malloc() and free().

When the process ends, no matter what the state of heap/stack is, everything is reclaimed by the OS, thus ensuring no memory is leaked.

But not calling free() would be an issue, if you have written a long running program, like a web service or any other service which is running for long time.

Common Memory Management errors:

There are a number of common errors that arise in the use of malloc() and free().

  1. Forgetting To Allocate Memory
  2. Not Allocating Enough Memory
  3. Forgetting to Initialize Allocated Memory
  4. Forgetting To Free Memory
  5. Freeing Memory Before You Are Done With It
  6. Freeing Memory Repeatedly
  7. Calling free() Incorrectly

It Compiled or It Ran != IT IS CORRECT

Just because a program compiled(maybe with warnings or without warnings) or ran even once or an awesome number of times correctly, does not mean that the program that is written is correct.

Many events may have conspired against you to reach this conclusion, but then a slight change in any item makes it fail.
A common programmer’s reaction is: “But it was working last time and many times! This is wrong! The compiler is wrong! The OS is faulty!”.

But the problem is usually right where you think it would be, in your code. Get to work and debug it before you blame those other components.


Recent Posts

Categories

GiottoPress by Enrique Chavez