Memory Leaks

Can any one explain about what is "Memory leaks" and where it's used?. I studied the Materials that is not understandable.
Sometimes memory is allocated to store something. That memory should be deallocated and make available for reuse when the object is no longer needed.

It is possible to get to a situation where the memory has not been deallocated, and there is no way to do so. For example, if you lost track of what piece of memory it is. Such memory, that should have been deallocated and made available for reuse but wasn't and can't be, is "leaked".
Memory leak in one of it's simplest forms.



1
2
3
4
5
6
7
8
9
10
int main()
{
  while(true)             // loop endlessly
  {                       // scope starts
    int * x = new int;    // allocates memory on the heap
    *x = 0xFF;            // puts data in allocated memory
  }                       // scope ends, reference to x lost permanently
                          //   can never delete x, memory leaked
  return 0;               // never reaches return statement
}
Last edited on
what is "Memory leaks" and where it's used?.

You may be confused. A memory leak is a bug, not something you do intentionally.
You've got three types of allocation: static, automatic, and dynamic.

I was going to describe it in-depth, but I found this answer on SE that answers the question, and looks quite nice.

http://stackoverflow.com/questions/408670/stack-static-and-heap-in-c

Stack = automatic, Heap = dynamic.

Anyway, memory leaks only occur when you're using dynamic allocation. You've got an example of memory leakin Hydranix's code sample.

The problem with this approach is that the memory you can get is finite. If you don't free the memory, you create a memory leak - meaning you can't access this memory anymore. If your application runs long enough and leaks memory, you will run out of memory, and your program will crash.

Nowadays we don't have much problems with memory leaks, since we use smart pointers - see std::unique_ptr (which is used the most) and std::shared_ptr.
These pointers can be used with both C programs, wheer you use SomeFunction to allocate the memory, and FreeFunction to free memory, or C++, where you don't provide any function - destructor deallocates memory(or, preferably, using RAII and smart pointers, destructor doesn't do anything explicitly).
Topic archived. No new replies allowed.