<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Freya.no &#187; scoped_ptr</title>
	<atom:link href="http://wp.freya.no/tag/scoped_ptr/feed/" rel="self" type="application/rss+xml" />
	<link>http://wp.freya.no</link>
	<description>Knowledge is power</description>
	<lastBuildDate>Wed, 28 Jul 2010 16:50:48 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Say goodbye to memory leaks in C++ with Boost!</title>
		<link>http://wp.freya.no/c/say-goodbye-to-memory-leaks-in-c-with-boost/</link>
		<comments>http://wp.freya.no/c/say-goodbye-to-memory-leaks-in-c-with-boost/#comments</comments>
		<pubDate>Fri, 28 Nov 2008 23:38:37 +0000</pubDate>
		<dc:creator>kent</dc:creator>
				<category><![CDATA[Dev]]></category>
		<category><![CDATA[Memorable]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[boost]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[memory leak]]></category>
		<category><![CDATA[scoped_ptr]]></category>

		<guid isPermaLink="false">http://wp.freya.no/?p=198</guid>
		<description><![CDATA[Intro A couple of months ago Boost came to me when I started in a new job just out of Uni, and I got impressed from day 1. Not only because in my previous experience Boost gave incredibly large errors[1] but what Boost really is and what the collection of libraries in Boost can do [...]]]></description>
			<content:encoded><![CDATA[<h1 id="toc-intro">Intro</h1>
<p>A couple of months ago Boost came to me when I started in a new job just out of Uni, and I got impressed from day 1. Not only because in my previous experience Boost gave incredibly large errors<sup><a href="http://wp.freya.no/lang-lang-pelikan" onclick="this.target='_self';this.href='#linknote-198-1';" id="noted-198-1" title="really really large">[1]</a></sup> but what Boost really is and what the collection of libraries in Boost can do to easily avoid many of the pitfalls with C++ programming.</p>
<p>Obtaining Boost is easy, simple and free. Boost&#8217;s license explicitly states it&#8217;s free as in free beer, and you can use Boost in commercial applications without breaking the license agreement.</p>
<h1 id="toc-how-to-build-boost">How to build Boost</h1>
<p>Most libraries in Boost are header only, so you don&#8217;t have to build Boost to get started with it. However, a couple of the libraries requires to be built.</p>
<h2 id="toc-linux">Linux</h2>
<p>Building Boost under Linux is very easy. Supposing you have a working development environment on your computer, you&#8217;ll only have to do these steps to build Boost.</p>
<pre>wget http://surfnet.dl.sourceforge.net/sourceforge/boost/boost_1_37_0.tar.gz
tar zxvf boost_1_37_0.tar.gz
cd boost_1_37_0
./configure
make</pre>
<p>Then you&#8217;ll have a working Linux build of Boost.</p>
<h2 id="toc-windows">Windows</h2>
<p>Building Boost on Windows is a bit harder than on Linux, but it&#8217;s not rocket science <img src='http://wp.freya.no/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>
<ol>
<li>Download and extract Boost to some folder.</li>
<li>Download bjam.exe and put it in the root Boost folder.</li>
<li>Invoke bjam with <tt>stage=complete</tt> + the options from the <a href="http://www.boost.org/doc/tools/build/doc/html/jam/usage.html">docs</a>.</li>
<li>Wait</li>
<li>Now you should have a complete set of libraries.</li>
</ol>
<h1 id="toc-example-1">Example 1</h1>
<h2 id="toc-memory-leak">Memory leak</h2>
<pre class="brush: cpp;">/*
 * C++ example with a memory leak in an exception
 */

#include &lt;iostream&gt;

void throwErrorWithMemLeak()
{
    try
    {
        // Allocate 1kB buffer
        char *buffer = new char[1024];

        // Throw
        throw 1;

        // Free up buffer
        delete buffer;
    }
    catch(const int e)
    {
        // printf(&quot;We have a memory leak\n&quot;);
    }
}

int main(int args, char **argc)
{
    // A simple case of when an exception leads to a memory leak

    // Iterate the throwing function 1024 times, creating a 1MB memeory leak
    for (size_t i=0; i&lt;1024; i++)
    {
        throwErrorWithMemLeak();
    }

    return 0;
}
</pre>
<p>Compile with</p>
<pre>g++ -ggdb3 ex1_memleak.cpp -o ex1_memleak</pre>
<p>And run it with valgrind to see the memory leak in action.</p>
<pre>valgrind ./ex1_memleak --leak-check=full
==21831== Memcheck, a memory error detector.
==21831== Copyright (C) 2002-2007, and GNU GPL'd, by Julian Seward et al.
==21831== Using LibVEX rev 1854, a library for dynamic binary translation.
==21831== Copyright (C) 2004-2007, and GNU GPL'd, by OpenWorks LLP.
==21831== Using valgrind-3.3.1, a dynamic binary instrumentation framework.
==21831== Copyright (C) 2000-2007, and GNU GPL'd, by Julian Seward et al.
==21831== For more details, rerun with: -v
==21831==
==21831==
==21831== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 4 from 1)
==21831== malloc/free: in use at exit: 1,048,576 bytes in 1,024 blocks.
==21831== malloc/free: 2,048 allocs, 1,024 frees, 1,167,360 bytes allocated.
==21831== For counts of detected errors, rerun with: -v
==21831== searching for pointers to 1,024 not-freed blocks.
==21831== checked 158,760 bytes.
==21831==
==21831== LEAK SUMMARY:
<span style="color: #ff0000"><strong>==21831==    definitely lost: 1,048,576 bytes in 1,024 blocks.</strong></span>
==21831==      possibly lost: 0 bytes in 0 blocks.
==21831==    still reachable: 0 bytes in 0 blocks.
==21831==         suppressed: 0 bytes in 0 blocks.</pre>
<p>As you can see, we&#8217;ve lost 1 megabyte of memory into the void. If this were a long running program, even small memory leaks could be disastrous if it&#8217;s allowed to grow unlimited.</p>
<h2 id="toc-no-memory-leak">No memory leak</h2>
<pre class="brush: cpp;">/*
 * C++ example without a memory leak in an exception
 */

#include &lt;iostream&gt;

#include &lt;boost/scoped_ptr.hpp&gt;

void throwErrorWithMemLeak()
{
    try
    {
        // Allocate 1kB buffer in an scoped pointer
        boost::scoped_ptr&lt;char&gt; buffer( new char[1024] );

        // Throw
        throw 1;

        // Free up buffer (we really don't need this)
        // scoped_ptr.reset( 0 );
    }
    catch(const int e)
    {
    }
}

int main(int args, char **argc)
{
    // A simple case of when an exception doesn't lead to a memory leak

    // Iterate the throwing function 1024 times, creating a possible 1MB
    // memory leak, but scoped_ptr prevents it gracefully.
    for (size_t i=0; i&lt;1024; i++)
    {
        throwErrorWithMemLeak();
    }

    return 0;
}
</pre>
<p>Compile with</p>
<pre>g++ -ggdb3 -I../boost_1_37_0/ ex1_no_memleak.cpp -o ex1_no_memleak</pre>
<p>Run with valgrind</p>
<pre>valgrind ./ex1_no_memleak
==21902== Memcheck, a memory error detector.
==21902== Copyright (C) 2002-2007, and GNU GPL'd, by Julian Seward et al.
==21902== Using LibVEX rev 1854, a library for dynamic binary translation.
==21902== Copyright (C) 2004-2007, and GNU GPL'd, by OpenWorks LLP.
==21902== Using valgrind-3.3.1, a dynamic binary instrumentation framework.
==21902== Copyright (C) 2000-2007, and GNU GPL'd, by Julian Seward et al.
==21902== For more details, rerun with: -v
==21902==
==21902== ERROR SUMMARY: 1024 errors from 1 contexts (suppressed: 4 from 1)
==21902== malloc/free: in use at exit: 0 bytes in 0 blocks.
==21902== malloc/free: 2,048 allocs, 2,048 frees, 1,167,360 bytes allocated.
==21902== For counts of detected errors, rerun with: -v
<span style="color: #ff0000">==21902== All heap blocks were freed -- no leaks are possible.</span></pre>
<p>No memory leaks!</p>
<p>This is only one small fraction of Boost, but yet a very powerful one. I&#8217;m in awe over Boost!
<div class="alt">Linknotes:
<ol>
<li id="linknote-198-1"><a href="http://wp.freya.no/lang-lang-pelikan">really really large</a>  <a href="#noted-198-1"><strong>&#8617;</strong></a></ol>
</div>
 <img src="http://wp.freya.no/wp-content/plugins/feed-statistics.php?view=1&post_id=198" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://wp.freya.no/c/say-goodbye-to-memory-leaks-in-c-with-boost/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
