Memory leak

From Jonathan Gardner's Tech Wiki
Jump to: navigation, search

Overview

The Memory Leak is a very common bug that is notoriously difficult to identify let alone diagnose and fix.

Understanding it sooner rather than later may save a lot of headache and pain.

Cause

The memory leak bug is caused by a program that allocates but does not free memory erroneously. That is, in the normal course of operation, programs will request a certain amount of memory from time to time to store data. When it is done using it, it should free the memory or re-purpose it. If the program has a memory leak, over time, it loses track of memory it has allocated or doesn't free up the memory once it is no longer needed.

Related to the memory leak is Poor resource allocation, which occurs when memory is not managed effectively.

Symptoms

Typically, the memory leak is manifested by a slow growth in memory without a corresponding growth in the amount of memory that should be necessary to run the program. For instance, a program might require a static amount of memory, but if it grows over time, then it likely has a memory leak. Another program might require a few kilobytes per record, but over time, that grows into tens and hundreds of kilobytes per record if it has a memory leak.

Identification

In languages like C with explicit memory management, identification is a matter of finding areas that are allocated but not freed. Languages like C++ provide some templates that make managing the memory lifecycle a little easier. Some programs exist to analyze these languages for memory leaks.

In languages without explicit memory management (Java, Python, Ruby, Javascript), memory leaks should not exist at all. However, Circular references may cause memory leaks if the memory manager does not correctly identify and free them. Some implementations of these languages may have memory leaks in their own right. Languages such as Python and Perl allocate memory but never free it, although they do repurpose it, so they might incorrectly be identified as a memory leak when really it's just poor resource management.

Correction

The correction is to free the memory when it is not longer needed.

Note that in fixing the correction, you might run into cases where the same memory is freed twice. Careful programming practices should eliminate the possibilities of both.