What is Memory Leak & How can we avoid Memory Leak

Java

Memory leak occurs when programmers create a memory in heap and forget to delete it.

Memory leaks are particularly serious issues for programs which by definition never terminate.

Usually developers talk about memory leaks but when you ask them what that means many have no idea. To prevent these situations, Lets discuss about memory lean in detail.

Memory that is not deallocated when it is no longer needed, and is no longer “reachable”. For instance, if I use “new” to instantiate an object, but I don’t use “delete” when I’m done with it (and my pointer has gone out of scope or something).

If data is not freed when there are no longer has any references to it, that data is unreachable. Basically, if you don’t free/delete data allocated on the heap, it becomes unusable and simply wastes memory.

There may be cases where a pointer is lost but the data is still accessible. For example, if you store the pointer in an int, or store an offset to the pointer (using pointer arithmetic), you can still get the original pointer back.

In this above definition, data is handled by garbage collectors, which keep track of the number of references to the data.

It can also be referred as, memory is essentially leaked if it is not freed/deleted when last used. It may be referenced, and immediately free-able, but the mistake has been made not to do so. There may be a valid reason (e.g. in the case where a destructor has some weird side effect), but that indicates bad program design.

This second type of memory leaking often happens when writing small programs which use file IO. You open the file, write your data, but don’t close it once you’re done. The FILE* may still be within scope, and easily closeable.

In this second definition, data is not handled by garbage collectors, unless the compiler/interpreter is smart (or dumb) enough to know it won’t be used any longer, and this freeing the data won’t cause any side effects.

The best way to prevent them probably depends on who you ask and what language you are using. Garbage collection is a good solution for it, of course, but there may be some overhead associated with this, which isn’t a big deal unless you performance is your primary concern. Garbage collection may not always be available, again, depending on the language you are using.

Alternatively, you can make sure you have the appropriate deletes and/or destructors in place.

Techniques for preventing / detecting memory leaks:

  • Consider your algorithm in terms of memory consumption.
  • Profile your application. You can use memory debugger tools find leaks.
  • Black-box testing. Watch what happens to your compiled code after you feed it large data sets, or allow it to run for long periods of time. See if its memory footprint has a tendency to grow without limit.