Chapter 8. Memory Leaks

By definition, a memory leak is a situation where we allocate some memory from the heap—in C++ by using the new operator, and in C by using malloc() or calloc()—then assign the address of this memory to a pointer, and somehow lose this value either by letting the pointer go out of scope:

{
  MyClass* my_class_object = new MyClass;
  DoSomething(my_class_object);
} // memory leak!!!

or by assigning some other value to it:

MyClass* my_class_object = new MyClass;
DoSomething(my_class_object);
my_class_object = NULL; // memory leak!!!

There are also situations when programmers keep allocating new memory and do not lose any pointers to it, but keep pointers to objects that the program is not going to use anymore. The latter is not formally a memory leak, but leads to the same situation: a program running out of memory. We’ll leave the latter error to the attention of the programmer, and concentrate on the first one—the “formal” memory leak.

Consider two objects containing pointers to each other (Figure 8-1). This situation is known as a “circular reference.” Pointers exist to A and to B, but if there are no other pointers to at least one of these objects from somewhere else, there is no way to reclaim the memory for either variable and therefore you create a memory leak. These two objects will live happily ever after and will never be destroyed. Now consider the opposite example. Suppose we have a class with a method that can be run in a separate thread: ...

Get Safe C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.