Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to guard against memory leaks?

I was recently interviewing for a C++ position, and I was asked how I guard against creating memory leaks. I know I didn't give a satisfactory answer to that question, so I'm throwing it to you guys. What are the best ways to guard against memory leaks?

Thanks!

like image 721
just_wes Avatar asked Feb 02 '10 16:02

just_wes


People also ask

What is the main cause of memory leaks?

DEFINITION A memory leak is the gradual deterioration of system performance that occurs over time as the result of the fragmentation of a computer's RAM due to poorly designed or programmed applications that fail to free up memory segments when they are no longer needed.

Which of the following best suits for memory leak occur?

The correct option is (C) Program does not free the memory which is allocated dynamically. Know how a when a Memory Leak can occur: When poorly designed programs or applications fail to free up their memory that is no longer necessary then there is a Memory Leak.


12 Answers

What all the answers given so far boil down to is this: avoid having to call delete.

Any time the programmer has to call delete, you have a potential memory leak. Instead, make the delete call happen automatically. C++ guarantees that local objects have their destructors called when they go out of scope. Use that guarantee to ensure your memory allocations are automatically deleted.

At its most general, this technique means that every memory allocation should be wrapped inside a simple class, whose constructor allocates the necessary memory, and destructor releases it.

Because this is such a commonly-used and widely applicable technique, smart pointer classes have been created that reduce the amount of boilerplate code. Rather than allocating memory, their constructors take a pointer to the memory allocation already made, and stores that. When the smart pointer goes out of scope, it is able to delete the allocation.

Of course, depending on usage, different semantics may be called for. Do you just need the simple case, where the allocation should last exactly as long as the wrapper class lives? Then use boost::scoped_ptr or, if you can't use boost, std::auto_ptr. Do you have an unknown number of objects referencing the allocation with no knowledge of how long each of them will live? Then the reference-counted boost::shared_ptr is a good solution.

But you don't have to use smart pointers. The standard library containers do the trick too. They internally allocate the memory required to store copies of the objects you put into them, and they release the memory again when they're deleted. So the user doesn't have to call either new or delete.

There are countless variations of this technique, changing whose responsibility it is to create the initial memory allocation, or when the deallocation should be performed.

But what they all have in common is the answer to your question: The RAII idiom: Resource Acquisition Is Initialization. Memory allocations are a kind of resource. Resources should be acquired when an object is initialized, and released by the object itslef, when it is destroyed.

Make the C++ scope and lifetime rules do your work for you. Never ever call delete outside of a RAII object, whether it is a container class, a smart pointer or some ad-hoc wrapper for a single allocation. Let the object handle the resource assigned to it.

If all delete calls happen automatically, there's no way you can forget them. And then there's no way you can leak memory.

like image 172
jalf Avatar answered Oct 01 '22 14:10

jalf


  1. Don't allocate memory on the heap if you don't need to. Most work can be done on the stack, so you should only do heap memory allocations when you absolutely need to.

  2. If you need a heap-allocated object that is owned by a single other object then use std::auto_ptr.

  3. Use standard containers, or containers from Boost instead of inventing your own.

  4. If you have an object that is referred to by several other objects and is owned by no single one in particular then use either std::tr1::shared_ptr or std::tr1::weak_ptr -- whichever suits your use case.

  5. If none of these things match your use case then maybe use delete. If you do end up having to manually manage memory then just use memory leak detection tools to make sure that you aren't leaking anything (and of course, just be careful). You shouldn't ever really get to this point though.

like image 24
Peter Alexander Avatar answered Oct 01 '22 13:10

Peter Alexander


replace new with shared_ptr's. Basically RAII. make code exception safe. Use the stl everywhere possible. If you use reference counting pointers make sure that they don't form cycles. SCOPED_EXIT from boost is also very useful.

like image 32
Chris H Avatar answered Oct 01 '22 12:10

Chris H


You'd do well to read up on RAII.

like image 43
ScaryAardvark Avatar answered Oct 01 '22 13:10

ScaryAardvark


  1. (Easy) Never ever let a raw pointer own a object (search your code for the regexp "\= *new". Use shared_ptr or scoped_ptr instead, or even better, use real variables instead of pointers as often as you can.

  2. (Hard) Make sure you don't have any circular references, with shared_ptrs pointing to each other, use weak_ptr to break them.

Done!

like image 31
Viktor Sehr Avatar answered Oct 01 '22 13:10

Viktor Sehr


Use all kind of smart pointers.

Use certain strategy for creation and deletion of objects, like who creates that is responsible for delete.

like image 39
Mykola Golubyev Avatar answered Oct 01 '22 12:10

Mykola Golubyev


  • make sure that you understand exactly how an object will be deleted everytime you create one
  • make sure you understand who owns the pointer every time one is returned to you
  • make sure your error paths dispose of objects you have created appropriately
  • be paranoid about the above
like image 43
doron Avatar answered Oct 01 '22 14:10

doron


In addition to the advice about RAII, remember to make your base class destructor virtual if there are any virtual functions.

like image 30
Chris Card Avatar answered Oct 01 '22 13:10

Chris Card


To avoid memory leaks, what you must do is to have a clear and definite notion of who is responsible for deleting any dynamically allocated object.

C++ allows construction of objects on the stack (i.e. as kind-of local variables). This binds creation and destruction the the control flow: an objects is created when program execution reaches its declaration, and the object is destroyed when execution escapes the block in which that declaration was made. Whenever allocation need matches that pattern, then use it. This will save you much of the trouble.

For other usages, if you can define and document a clear notion of responsibility, then this may work fine. For instance, you have a method or a function which returns a pointer to a newly allocated object, and you document that the caller becomes responsible for ultimately deleting that instance. Clear documentation coupled with good programmer discipline (something which is not easily achieved !) can solve many remaining problems of memory management.

In some situations, including undisciplined programmers and complex data structures, you may have to resort to more advanced techniques, such as reference counting. Each object is awarded a "counter" which is the number of other variables which point to it. Whenever a piece of code decides to no longer point to the object, the counter is decreased. When the counter reaches zero, the object is deleted. Reference counting requires strict counter handling. This can be done with so-called "smart pointers": these are object which are functionally pointers, but which automatically adjust the counter upon their own creation and destruction.

Reference counting works quite good in many situations, but they cannot handle cyclic structures. So for the most complex situations, you have to resort to the heavy artillery, i.e. a garbage collector. The one I link to is the GC for C and C++ written by Hans Boehm, and it has been used in some rather big projects (e.g. Inkscape). The point of a garbage collector is to maintain a global view on the complete memory space, to know whether a given instance is still in use or not. This is the right tool when local-view tools, such as reference counting, are not enough. One could argue that, at that point, one should ask oneself whether C++ is the right language for the problem at hand. Garbage collection works best when the language is cooperative (this unlocks a host of optimizations which are not doable when the compiler is unaware of what happens with memory, as a typical C or C++ compiler).

Note that none of the techniques described above allows the programmer to stop thinking. Even a GC can suffer from memory leaks, because it uses reachability as an approximation of future usage (there are theoretical reasons which imply that it is not possible, in full generality, to accurately detect all objects which will not be used thereafter). You may still have to set some fields to NULL to inform the GC that you will no longer access an object through a given variable.

like image 26
Thomas Pornin Avatar answered Oct 01 '22 13:10

Thomas Pornin


I start by reading the following: https://stackoverflow.com/search?q=%5Bc%2B%2B%5D+memory+leak

like image 38
S.Lott Avatar answered Oct 01 '22 14:10

S.Lott


A very good way is using Smart Pointers, the boost/tr1::shared_ptr. The memory will be free'd, once the (stack allocated) smart pointer goes out of scope.

like image 38
DerKuchen Avatar answered Oct 01 '22 14:10

DerKuchen


You can use the utility. If you work on Linux - use valgrid (it's free). Use deleaker on Windows.

like image 26
John Smith Avatar answered Oct 01 '22 12:10

John Smith