Memory leak

From Cppwiki

Jump to: navigation, search

A memory leak occurs when a program allocates memory and does not deallocate that memory before the program is closed, or all handles to that memory are lost.

Contents

Examples of Memory Leaks

int* i = new int[10];
i = new int[20];

Here, the address of the allocated data has been overridden by the address returned from the second call to new[] before the first allocated chunk of data was delete[]ed.

int main() {
  int* i = new int;
}

Here the program ended without a corresponding call to delete.

Opinion: twincest
it's worth noting that in the second case, even though the memory is not freed, the OS will free the memory at exit; i wouldn't call this a memory leak. the former case is a leak because memory has been allocated, but not freed, and there are no references to it.

Avoiding Memory Leaks

To avoid memory leaks, one should first of all consider using a standard container or a smart pointer. These library features handle memory allocation and deallocation themselves, and are a lot easier to work with than raw pointers.

If such are not able to be used, one must ensure they follow the rules:

Allocation Symmetry

There are three basic rules you should adhere to when allocating and deallocating memory:

These rules MUST be followed, even if an exception is thrown.

Other resources

When using libraries or APIs that return pointers or handles to resources that aren't themselves considered a block of memory, it's quite common to leak these resources as well. Any time a library allocates memory, or returns a handle or pointer back to your program, be careful to check the documentation to see what the correct way of freeing these resources is as well.

You may also wish to consider using a debug allocator for automated tracking of the most common sorts of memory leaks.

See also

http://parashift.com/c++-faq-lite/containers.html#faq-34.1

Personal tools