General guidelines to avoid memory leaks in C++


Question

What are some general tips to make sure I don't leak memory in C++ programs? How do I figure out who should free memory that has been dynamically allocated?

1
125
9/27/2016 2:57:52 PM

Accepted Answer

Instead of managing memory manually, try to use smart pointers where applicable.
Take a look at the Boost lib, TR1, and smart pointers.
Also smart pointers are now a part of C++ standard called C++11.

38
11/28/2012 4:23:04 PM

I thoroughly endorse all the advice about RAII and smart pointers, but I'd also like to add a slightly higher-level tip: the easiest memory to manage is the memory you never allocated. Unlike languages like C# and Java, where pretty much everything is a reference, in C++ you should put objects on the stack whenever you can. As I've see several people (including Dr Stroustrup) point out, the main reason why garbage collection has never been popular in C++ is that well-written C++ doesn't produce much garbage in the first place.

Don't write

Object* x = new Object;

or even

shared_ptr<Object> x(new Object);

when you can just write

Object x;

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon