General guidelines to avoid memory leaks in C++

dulipishi picture dulipishi · Sep 16, 2008 · Viewed 119.4k times · Source

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?

Answer

Ross Smith picture Ross Smith · Sep 17, 2008

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;