<p>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?</p>

[{'answer_id': 76814, 'author': 'DougN', 'author_id': 7442, 'author_profile': 'https://Stackoverflow.com/users/7442', 'pm_score': 2, 'selected': False, 'text': '<p>User smart pointers everywhere you can!  Whole classes of memory leaks just go away.</p>\n'}, {'answer_id': 76820, 'author': 'Doug T.', 'author_id': 8123, 'author_profile': 'https://Stackoverflow.com/users/8123', 'pm_score': 5, 'selected': False, 'text': '<p>You\'ll want to look at smart pointers, such as <a href="http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/shared_ptr.htm" rel="noreferrer">boost\'s smart pointers</a>.</p>\n\n<p>Instead of </p>\n\n<pre><code>int main()\n{ \n    Object* obj = new Object();\n    //...\n    delete obj;\n}\n</code></pre>\n\n<p>boost::shared_ptr will automatically delete once the reference count is zero:</p>\n\n<pre><code>int main()\n{\n    boost::shared_ptr&lt;Object&gt; obj(new Object());\n    //...\n    // destructor destroys when reference count is zero\n}\n</code></pre>\n\n<p>Note my last note, "when reference count is zero, which is the coolest part. So If you have multiple users of your object, you won\'t have to keep track of whether the object is still in use. Once nobody refers to your shared pointer, it gets destroyed.</p>\n\n<p>This is not a panacea, however. Though you can access the base pointer, you wouldn\'t want to pass it to a 3rd party API unless you were confident with what it was doing. Lots of times, your "posting" stuff to some other thread for work to be done AFTER the creating scope is finished. This is common with PostThreadMessage in Win32:</p>\n\n<pre><code>void foo()\n{\n   boost::shared_ptr&lt;Object&gt; obj(new Object()); \n\n   // Simplified here\n   PostThreadMessage(...., (LPARAM)ob.get());\n   // Destructor destroys! pointer sent to PostThreadMessage is invalid! Zohnoes!\n}\n</code></pre>\n\n<p>As always, use your thinking cap with any tool...</p>\n'}, {'answer_id': 76838, 'author': 'Seth Morris', 'author_id': 13434, 'author_profile': 'https://Stackoverflow.com/users/13434', 'pm_score': 2, 'selected': False, 'text': '<p>Share and know memory ownership rules across your project. Using the COM rules makes for the best consistency ([in] parameters are owned by the caller, callee must copy; [out] params are owned by the caller, callee must make a copy if keeping a reference; etc.)</p>\n'}, {'answer_id': 76844, 'author': 'Andri Möll', 'author_id': 13719, 'author_profile': 'https://Stackoverflow.com/users/13719', 'pm_score': 6, 'selected': True, 'text': '<p>Instead of managing memory manually, try to use smart pointers where applicable.<br />\nTake a look at the <a href="http://www.boost.org/" rel="noreferrer">Boost lib</a>, <a href="http://en.wikipedia.org/wiki/Technical_Report_1" rel="noreferrer">TR1</a>, and <a href="http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/smart_ptr.htm" rel="noreferrer">smart pointers</a>.<br />\nAlso smart pointers are now a part of C++ standard called <a href="http://en.wikipedia.org/wiki/Smart_pointer" rel="noreferrer">C++11</a>.<br /></p>\n'}, {'answer_id': 76850, 'author': 'Hank', 'author_id': 7610, 'author_profile': 'https://Stackoverflow.com/users/7610', 'pm_score': 4, 'selected': False, 'text': '<p>Read up on <a href="http://en.wikipedia.org/wiki/Resource_acquisition_is_initialization" rel="noreferrer">RAII</a> and make sure you understand it.</p>\n'}, {'answer_id': 76852, 'author': 'Justin Rudd', 'author_id': 12968, 'author_profile': 'https://Stackoverflow.com/users/12968', 'pm_score': 1, 'selected': False, 'text': "<p>If you can, use boost shared_ptr and standard C++ auto_ptr.  Those convey ownership semantics.</p>\n\n<p>When you return an auto_ptr, you are telling the caller that you are giving them ownership of the memory.</p>\n\n<p>When you return a shared_ptr, you are telling the caller that you have a reference to it and they take part of the ownership, but it isn't solely their responsibility.</p>\n\n<p>These semantics also apply to parameters.  If the caller passes you an auto_ptr, they are giving you ownership.</p>\n"}, {'answer_id': 76859, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p><strong>valgrind</strong> is a good tool to check your programs memory leakages at runtime, too.</p>\n\n<p>It is available on most flavors of Linux (including Android) and on Darwin.</p>\n\n<p>If you use to write unit tests for your programs, you should get in the habit of systematicaly running valgrind on tests. It will potentially avoid many memory leaks at an early stage. It is also usually easier to pinpoint them in simple tests that in a full software. </p>\n\n<p>Of course this advice stay valid for any other memory check tool.</p>\n'}, {'answer_id': 76866, 'author': 'Jason Dagit', 'author_id': 5113, 'author_profile': 'https://Stackoverflow.com/users/5113', 'pm_score': 3, 'selected': False, 'text': '<p>One technique that has become popular with memory management in C++ is <a href="http://en.wikipedia.org/wiki/Resource_acquisition_is_initialization" rel="noreferrer">RAII</a>.  Basically you use constructors/destructors to handle resource allocation.  Of course there are some other obnoxious details in C++ due to exception safety, but the basic idea is pretty simple.</p>\n\n<p>The issue generally comes down to one of ownership.  I highly recommend reading the Effective C++ series by Scott Meyers and Modern C++ Design by Andrei Alexandrescu.</p>\n'}, {'answer_id': 76876, 'author': 'Seth Morris', 'author_id': 13434, 'author_profile': 'https://Stackoverflow.com/users/13434', 'pm_score': 2, 'selected': False, 'text': "<p>If you can't/don't use a smart pointer for something (although that should be a huge red flag), type in your code with:</p>\n\n<pre><code>allocate\nif allocation succeeded:\n{ //scope)\n     deallocate()\n}\n</code></pre>\n\n<p>That's obvious, but make sure you type it <em>before</em> you type any code in the scope</p>\n"}, {'answer_id': 76878, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': "<p>Also, don't use manually allocated memory if there's a std library class (e.g. vector).  Make sure if you violate that rule that you have a virtual destructor.</p>\n"}, {'answer_id': 76906, 'author': 'Seth Morris', 'author_id': 13434, 'author_profile': 'https://Stackoverflow.com/users/13434', 'pm_score': -1, 'selected': False, 'text': "<p>Exactly one return from any function. That way you can do deallocation there and never miss it.</p>\n\n<p>It's too easy to make a mistake otherwise:</p>\n\n<pre><code>new a()\nif (Bad()) {delete a; return;}\nnew b()\nif (Bad()) {delete a; delete b; return;}\n... // etc.\n</code></pre>\n"}, {'answer_id': 76931, 'author': 'Null303', 'author_id': 13787, 'author_profile': 'https://Stackoverflow.com/users/13787', 'pm_score': 1, 'selected': False, 'text': '<p>If you are going to manage your memory manually, you have two cases:</p>\n\n<ol>\n<li>I created the object (perhaps indirectly, by calling a function that allocates a new object), I use it (or a function I call uses it), then I free it.</li>\n<li>Somebody gave me the reference, so I should not free it.</li>\n</ol>\n\n<p>If you need to break any of these rules, please document it.</p>\n\n<p>It is all about pointer ownership.</p>\n'}, {'answer_id': 76961, 'author': 'INS', 'author_id': 13136, 'author_profile': 'https://Stackoverflow.com/users/13136', 'pm_score': 0, 'selected': False, 'text': '<p>You can intercept the memory allocation functions and see if there are some memory zones not freed upon program exit (though it is not suitable for <em>all</em> the applications).</p>\n\n<p>It can also be done at compile time by replacing operators new and delete and other memory allocation functions.</p>\n\n<p>For example check in this <a href="http://www.scs.cs.nyu.edu/~dm/c++-new.html" rel="nofollow noreferrer">site</a> [Debugging memory allocation in C++]\nNote: There is a trick for delete operator also something like this:</p>\n\n<pre><code>#define DEBUG_DELETE PrepareDelete(__LINE__,__FILE__); delete\n#define delete DEBUG_DELETE\n</code></pre>\n\n<p>You can store in some variables the name of the file and when the overloaded delete operator will know which was the place it was called from. This way you can have the trace of every delete and malloc from your program. At the end of the memory checking sequence you should be able to report what allocated block of memory was not \'deleted\' identifying it by filename and line number which is I guess what you want.</p>\n\n<p>You could also try something like <a href="http://www.compuware.com/products/devpartner/visualc.htm" rel="nofollow noreferrer">BoundsChecker</a> under Visual Studio which is pretty interesting and easy to use.</p>\n'}, {'answer_id': 77035, 'author': 'DarenW', 'author_id': 10468, 'author_profile': 'https://Stackoverflow.com/users/10468', 'pm_score': 4, 'selected': False, 'text': '<p>Bah, you young kids and your new-fangled garbage collectors...</p>\n\n<p>Very strong rules on "ownership" - what object or part of the software has the right to delete the object.   Clear comments and wise variable names to make it obvious if a pointer "owns" or is "just look, don\'t touch".    To help decide who owns what, follow as much as possible the "sandwich" pattern within every subroutine or method.</p>\n\n<pre><code>create a thing\nuse that thing\ndestroy that thing\n</code></pre>\n\n<p>Sometimes it\'s necessary to create and destroy in widely different places; i think hard to avoid that.  </p>\n\n<p>In any program requiring complex data structures, i create a strict clear-cut tree of objects containing other objects - using "owner" pointers.  This tree models the basic hierarchy of  application domain concepts.  Example a 3D scene owns objects, lights, textures.   At the end of the rendering when the program quits, there\'s a clear way to destroy everything.   </p>\n\n<p>Many other pointers are defined as needed whenever one entity needs access another, to scan over arays or whatever; these are the "just looking". For the 3D scene example - an object uses a texture but does not own; other objects may use that same texture.  The destruction of an object does <em>not</em> invoke destruction of any textures. </p>\n\n<p>Yes it\'s time consuming but that\'s what i do.  I rarely have memory leaks or other problems.  But then i work in the limited arena of high-performance scientific, data acquisition and graphics software. I don\'t often deal transactions like in banking and ecommerce, event-driven GUIs or high networked asynchronous chaos.  Maybe the new-fangled ways have an advantage there!</p>\n'}, {'answer_id': 77040, 'author': 'screenglow', 'author_id': 424554, 'author_profile': 'https://Stackoverflow.com/users/424554', 'pm_score': 0, 'selected': False, 'text': '<p>We wrap all our allocation functions with a layer that appends a brief string at the front and a sentinel flag at the end. So for example you\'d have a call to "myalloc( pszSomeString, iSize, iAlignment ); or new( "description", iSize ) MyObject(); which internally allocates the specified size plus enough space for your header and sentinel. Of course, don\'t forget to comment this out for non-debug builds! It takes a little more memory to do this but the benefits far outweigh the costs. </p>\n\n<p>This has three benefits - first it allows you to easily and quickly track what code is leaking, by doing quick searches for code allocated in certain \'zones\' but not cleaned up when those zones should have freed. It can also be useful to detect when a boundary has been overwritten by checking to ensure all sentinels are intact. This has saved us numerous times when trying to find those well-hidden crashes or array missteps. The third benefit is in tracking the use of memory to see who the big players are - a collation of certain descriptions in a MemDump tells you when \'sound\' is taking up way more space than you anticipated, for example. </p>\n'}, {'answer_id': 77148, 'author': 'fabiopedrosa', 'author_id': 2731698, 'author_profile': 'https://Stackoverflow.com/users/2731698', 'pm_score': 3, 'selected': False, 'text': '<p>There\'s already a lot about how to not leak, but if you need a tool to help you track leaks take a look at:</p>\n\n<ul>\n<li><a href="http://www.compuware.com/products/devpartner/visualc.htm" rel="noreferrer">BoundsChecker</a> under VS </li>\n<li>MMGR C/C++ lib from FluidStudio\n<a href="http://www.paulnettle.com/pub/FluidStudios/MemoryManagers/Fluid_Studios_Memory_Manager.zip" rel="noreferrer">http://www.paulnettle.com/pub/FluidStudios/MemoryManagers/Fluid_Studios_Memory_Manager.zip</a> (its overrides the allocation methods and creates a report of the allocations, leaks, etc)</li>\n</ul>\n'}, {'answer_id': 77182, 'author': 'artificialidiot', 'author_id': 7988, 'author_profile': 'https://Stackoverflow.com/users/7988', 'pm_score': 0, 'selected': False, 'text': '<p>C++ is designed RAII in mind. There is really no better way to manage memory in C++ I think.\nBut be careful not to allocate very big chunks (like buffer objects) on local scope. It can cause stack overflows and, if there is a flaw in bounds checking while using that chunk, you can overwrite other variables or return addresses, which leads to all kinds security holes.</p>\n'}, {'answer_id': 77234, 'author': 'eli', 'author_id': 5105, 'author_profile': 'https://Stackoverflow.com/users/5105', 'pm_score': 1, 'selected': False, 'text': '<p>Others have mentioned ways of avoiding memory leaks in the first place (like smart pointers).  But a profiling and memory-analysis tool is often the only way to track down memory problems once you have them.</p>\n\n<p><a href="http://valgrind.org/info/tools.html#memcheck" rel="nofollow noreferrer">Valgrind memcheck</a> is an excellent free one.</p>\n'}, {'answer_id': 77893, 'author': 'paercebal', 'author_id': 14089, 'author_profile': 'https://Stackoverflow.com/users/14089', 'pm_score': 7, 'selected': False, 'text': '<h2>Use <a href="http://en.wikipedia.org/wiki/RAII" rel="noreferrer">RAII</a></h2>\n\n<ul>\n<li><strong>Forget Garbage Collection</strong> (Use RAII instead). Note that even the Garbage Collector can leak, too (if you forget to "null" some references in Java/C#), and that Garbage Collector won\'t help you to dispose of resources (if you have an object which acquired a handle to a file, the file won\'t be freed automatically when the object will go out of scope if you don\'t do it manually in Java, or use the "dispose" pattern in C#).</li>\n<li><strong>Forget the "one return per function" rule</strong>. This is a good C advice to avoid leaks, but it is outdated in C++ because of its use of exceptions (use RAII instead).</li>\n<li>And while <strong>the "Sandwich Pattern"</strong> is a good C advice, it <strong>is outdated in C++</strong>  because of its use of exceptions (use RAII instead).</li>\n</ul>\n\n<p>This post seem to be repetitive, but in C++, the most basic pattern to know is <a href="http://en.wikipedia.org/wiki/RAII" rel="noreferrer">RAII</a>.</p>\n\n<p>Learn to use smart pointers, both from boost, TR1 or even the lowly (but often efficient enough) auto_ptr (but you must know its limitations).</p>\n\n<p>RAII is the basis of both exception safety and resource disposal in C++, and no other pattern (sandwich, etc.) will give you both (and most of the time, it will give you none).</p>\n\n<p>See below a comparison of RAII and non RAII code:</p>\n\n<pre><code>void doSandwich()\n{\n   T * p = new T() ;\n   // do something with p\n   delete p ; // leak if the p processing throws or return\n}\n\nvoid doRAIIDynamic()\n{\n   std::auto_ptr&lt;T&gt; p(new T()) ; // you can use other smart pointers, too\n   // do something with p\n   // WON\'T EVER LEAK, even in case of exceptions, returns, breaks, etc.\n}\n\nvoid doRAIIStatic()\n{\n   T p ;\n   // do something with p\n   // WON\'T EVER LEAK, even in case of exceptions, returns, breaks, etc.\n}\n</code></pre>\n\n<h2>About <a href="http://en.wikipedia.org/wiki/RAII" rel="noreferrer">RAII</a></h2>\n\n<p>To summarize (after the comment from <i>Ogre Psalm33</i>), RAII relies on three concepts:</p>\n\n<ul>\n<li><b>Once the object is constructed, it just works!</b> Do acquire resources in the constructor.</li>\n<li><b>Object destruction is enough!</b> Do free resources in the destructor.</li>\n<li><b>It\'s all about scopes!</b> Scoped objects (see doRAIIStatic example above) will be constructed at their declaration, and will be destroyed the moment the execution exits the scope, no matter how the exit (return, break, exception, etc.).</li>\n</ul>\n\n<p>This means that in correct C++ code, most objects won\'t be constructed with <code>new</code>, and will be declared on the stack instead. And for those constructed using <code>new</code>, all will be somehow <i>scoped</i> (e.g. attached to a smart pointer).</p>\n\n<p>As a developer, this is very powerful indeed as you won\'t need to care about manual resource handling (as done in C, or for some objects in Java which makes intensive use of <code>try</code>/<code>finally</code> for that case)...</p>\n\n<h2>Edit (2012-02-12)</h2>\n\n<blockquote>\n  <p>"scoped objects ... will be destructed ... no matter the exit" that\'s not entirely true. there are ways to cheat RAII. any flavour of terminate() will bypass cleanup. exit(EXIT_SUCCESS) is an oxymoron in this regard.</p>\n  \n  <p>– <a href="https://stackoverflow.com/users/456/wilhelmtell">wilhelmtell</a></p>\n</blockquote>\n\n<p><a href="https://stackoverflow.com/users/456/wilhelmtell">wilhelmtell</a> is quite right about that: There are <em>exceptional</em> ways to cheat RAII, all leading to the process abrupt stop.</p>\n\n<p>Those are <strong>exceptional</strong> ways because C++ code is not littered with terminate, exit, etc., or in the case with exceptions, we do want an <a href="https://stackoverflow.com/questions/1104136/c-raii-not-working">unhandled exception</a> to crash the process and core dump its memory image as is, and not after cleaning.</p>\n\n<p>But we must still know about those cases because, while they rarely happen, they can still happen.</p>\n\n<p><i>(who calls <code>terminate</code> or <code>exit</code> in casual C++ code?... I remember having to deal with that problem when playing with <a href="http://www.opengl.org/resources/libraries/glut/" rel="noreferrer">GLUT</a>: This library is very C-oriented, going as far as actively designing it to make things difficult for C++ developers like not caring about <a href="http://www.opengl.org/resources/faq/technical/glut.htm#glot0070" rel="noreferrer">stack allocated data</a>, or having "interesting" decisions about <a href="http://www.opengl.org/resources/faq/technical/glut.htm#glot0090" rel="noreferrer">never returning from their main loop</a>... I won\'t comment about that)</i>.</p>\n'}, {'answer_id': 78019, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 8, 'selected': False, 'text': "<p>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.</p>\n\n<p>Don't write</p>\n\n<pre><code>Object* x = new Object;\n</code></pre>\n\n<p>or even</p>\n\n<pre><code>shared_ptr&lt;Object&gt; x(new Object);\n</code></pre>\n\n<p>when you can just write</p>\n\n<pre><code>Object x;\n</code></pre>\n"}, {'answer_id': 81039, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>One of the only examples about allocating and destroying in different places is thread creation (the parameter you pass).\nBut even in this case is easy.\nHere is the function/method creating a thread:</p>\n\n<pre><code>struct myparams {\nint x;\nstd::vector&lt;double&gt; z;\n}\n\nstd::auto_ptr&lt;myparams&gt; param(new myparams(x, ...));\n// Release the ownership in case thread creation is successfull\nif (0 == pthread_create(&amp;th, NULL, th_func, param.get()) param.release();\n...\n</code></pre>\n\n<p>Here instead the thread function</p>\n\n<pre><code>extern "C" void* th_func(void* p) {\n   try {\n       std::auto_ptr&lt;myparams&gt; param((myparams*)p);\n       ...\n   } catch(...) {\n   }\n   return 0;\n}\n</code></pre>\n\n<p>Pretty easyn isn\'t it? In case the thread creation fails the resource will be free\'d (deleted) by the auto_ptr, otherwise the ownership will be passed to the thread.\nWhat if the thread is so fast that after creation it releases the resource before the</p>\n\n<pre><code>param.release();\n</code></pre>\n\n<p>gets called in the main function/method? Nothing! Because we will \'tell\' the auto_ptr to ignore the deallocation.\nIs C++ memory management easy isn\'t it?\nCheers,</p>\n\n<p>Ema!</p>\n'}, {'answer_id': 81082, 'author': 'Rob', 'author_id': 9236, 'author_profile': 'https://Stackoverflow.com/users/9236', 'pm_score': 1, 'selected': False, 'text': "<p>For MSVC only, add the following to the top of each .cpp file:</p>\n\n<pre><code>#ifdef _DEBUG\n#define new DEBUG_NEW\n#endif\n</code></pre>\n\n<p>Then, when debugging with VS2003 or greater, you will be told of any leaks when your program exits (it tracks new/delete).  It's basic, but it has helped me in the past.</p>\n"}, {'answer_id': 81141, 'author': 'ugasoft', 'author_id': 10120, 'author_profile': 'https://Stackoverflow.com/users/10120', 'pm_score': 3, 'selected': False, 'text': '<p>Great question!</p>\n\n<p>if you are using c++ and you are developing real-time CPU-and-memory boud application (like games) you need to write your own Memory Manager.</p>\n\n<p>I think the better you can do is merge some interesting works of various authors, I can give you some hint:</p>\n\n<ul>\n<li><p>Fixed size allocator is heavily discussed, everywhere in the net</p></li>\n<li><p>Small Object Allocation was introduced by Alexandrescu in 2001 in his perfect book "Modern c++ design"</p></li>\n<li><p>A great advancement (with source code distributed) can be found in an amazing article in Game Programming Gem 7 (2008) named "High Performance Heap allocator" written by Dimitar Lazarov</p></li>\n<li><p>A great list of resources can be found in <a href="http://entland.homelinux.com/blog/2008/08/19/practical-efficient-memory-management/" rel="noreferrer">this</a> article</p></li>\n</ul>\n\n<p>Do not start writing a noob unuseful allocator by yourself... DOCUMENT YOURSELF first.</p>\n'}, {'answer_id': 81146, 'author': 'Jonathan', 'author_id': 14850, 'author_profile': 'https://Stackoverflow.com/users/14850', 'pm_score': 2, 'selected': False, 'text': "<p>A frequent source of these bugs is when you have a method that accepts a reference or pointer to an object but leaves ownership unclear.  Style and commenting conventions can make this less likely.</p>\n\n<p>Let the case where the function takes ownership of the object be the special case.  In all situations where this happens, be sure to write a comment next to the function in the header file indicating this.  You should strive to make sure that in most cases the module or class which allocates an object is also responsible for deallocating it.</p>\n\n<p>Using const can help a lot in some cases.  If a function will not modify an object, and does not store a reference to it that persists after it returns, accept a const reference.  From reading the caller's code it will be obvious that your function has not accepted ownership of the object.  You could have had the same function accept a non-const pointer, and the caller may or may not have assumed that the callee accepted ownership, but with a const reference there's no question.</p>\n\n<p>Do not use non-const references in argument lists.  It is very unclear when reading the caller code that the callee may have kept a reference to the parameter.</p>\n\n<p>I disagree with the comments recommending reference counted pointers.  This usually works fine, but when you have a bug and it doesn't work, especially if your destructor does something non-trivial, such as in a multithreaded program.  Definitely try to adjust your design to not need reference counting if it's not too hard.</p>\n"}, {'answer_id': 81538, 'author': 'Robert Gould', 'author_id': 15124, 'author_profile': 'https://Stackoverflow.com/users/15124', 'pm_score': 2, 'selected': False, 'text': '<p>Tips in order of Importance:</p>\n\n<p>-Tip#1 Always remember to declare your destructors "virtual".</p>\n\n<p>-Tip#2 Use RAII</p>\n\n<p>-Tip#3 Use boost\'s smartpointers</p>\n\n<p>-Tip#4 Don\'t write your own buggy Smartpointers, use boost (on a project I\'m on right now I can\'t use boost, and I\'ve suffered having to debug my own smart pointers, I would definately not take the same route again, but then again right now I can\'t add boost to our dependencies)</p>\n\n<p>-Tip#5 If its some casual/non-performance critical (as in games with thousands of objects) work look at Thorsten Ottosen\'s boost pointer container</p>\n\n<p>-Tip#6 Find a leak detection header for your platform of choice such as Visual Leak Detection\'s "vld" header</p>\n'}, {'answer_id': 83353, 'author': 'Nemanja Trifunovic', 'author_id': 8899, 'author_profile': 'https://Stackoverflow.com/users/8899', 'pm_score': 0, 'selected': False, 'text': '<p>Manage memory the same way you manage other resources (handles, files, db connections, sockets...). GC would not help you with them either.</p>\n'}, {'answer_id': 83373, 'author': 'Ronny Brendel', 'author_id': 14114, 'author_profile': 'https://Stackoverflow.com/users/14114', 'pm_score': 1, 'selected': False, 'text': '<p>valgrind (only avail for *nix platforms) is a very nice memory checker</p>\n'}, {'answer_id': 103563, 'author': 'Jeroen Dirks', 'author_id': 7743, 'author_profile': 'https://Stackoverflow.com/users/7743', 'pm_score': 4, 'selected': False, 'text': "<p>Most memory leaks are the result of not being clear about object ownership and lifetime.</p>\n\n<p>The first thing to do is to allocate on the Stack whenever you can. This deals with most of the cases where you need to allocate a single object for some purpose.</p>\n\n<p>If you do need to 'new' an object then most of the time it will have a single obvious owner for the rest of its lifetime. For this situation I tend to use a bunch of collections templates that are designed for 'owning' objects stored in them by pointer. They are implemented with the STL vector and map containers but have some differences:</p>\n\n<ul>\n<li>These collections can not be copied or assigned to. (once they contain objects.)</li>\n<li>Pointers to objects are inserted into them.</li>\n<li>When the collection is deleted the destructor is first called on all objects in the collection. (I have another version where it asserts if destructed and not empty.)</li>\n<li>Since they store pointers you can also store inherited objects in these containers.</li>\n</ul>\n\n<p>My beaf with STL is that it is so focused on Value objects while in most applications objects are unique entities that do not have meaningful copy semantics required for use in those containers.</p>\n"}, {'answer_id': 426351, 'author': 'mh.', 'author_id': 44134, 'author_profile': 'https://Stackoverflow.com/users/44134', 'pm_score': 1, 'selected': False, 'text': '<ul>\n<li>Try to avoid allocating objects dynamically. As long as classes have appropriate constructors and destructors, use a variable of the class type, not a pointer to it, and you avoid dynamical allocation and deallocation because the compiler will do it for you.<br>\nActually that\'s also the mechanism used by "smart pointers" and referred to as RAII by some of the other writers ;-) . \n<li>When you pass objects to other functions, prefer reference parameters over pointers. This avoids some possible errors.\n<li>Declare parameters const, where possible, especially pointers to objects. That way objects can\'t be freed "accidentially" (except if you cast the const away ;-))).  \n<li>Minimize the number of places in the program where you do memory allocation and deallocation. E. g. if you do allocate or free the same type several times, write a function for it (or a factory method ;-)).<br>\nThis way you can create debug output (which addresses are allocated and deallocated, ...) easily, if required.\n<li>Use a factory function to allocate objects of several related classes from a single function.  \n<li>If your classes have a common base class with a virtual destructor, you can free all of them using the same function (or static method).\n<li>Check your program with tools like purify (unfortunately many $/€/...).   \n</ul>\n'}]
['https://Stackoverflow.com/questions/76796', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']