📄 memory leak detection in embedded systems linux journal.htm
字号:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"><head> <title>Memory Leak Detection in Embedded Systems | Linux Journal</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><base href="http://www.linuxjournal.com/" /><style type="text/css" media="all">@import "misc/drupal.css";</style> <style type="text/css" media="all">@import "sites/default/themes/linuxjournal/style.css";</style> <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon"/> <style type="text/css" media="all">@import "/sites/default/themes/linuxjournal/lj-added.css";</style> <script language="JavaScript" type="text/javascript" src="/local/lib/js/browser.js"></script> <script language="JavaScript" type="text/javascript" src="/local/lib/js/phpads.js"></script> <script language="JavaScript" type="text/javascript" src="http://ads.linuxjournal.com/adx.js"></script><!-- 03-Feb-2005 MRF Menu stuff not used anymore. <script language="JavaScript" type="text/javascript" src="/local/lib/doiMenu/js/doiMenuDOM.js"></script> <script language="JavaScript" type="text/javascript" src="/local/lib/doiMenu/js/functions.js"></script>--> <script language="JavaScript" type="text/javascript" src="/local/linuxjournal.js"></script> <script type="text/javascript"> </script></head><body bgcolor="#ffffff" ><div class="hide"><a href="#content" title="Skip navigation." accesskey="2">Skip navigation</a>.</div><table class="powerBarAd" width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td align="center"> <script language='JavaScript' type='text/javascript'> <!-- phpads_show_ad("http://ads.linuxjournal.com", "8"); //--> </script> <noscript> <p><a href='http://ads.linuxjournal.com/adclick.php?n=a6c85b67' target='_blank'> <img src='http://ads.linuxjournal.com/adview.php?what=zone:8&n=a6c85b67' border='0' alt='' /> </a></p> </noscript> </td> </tr></table><table id="primary-menu" summary="Navigation elements." border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <!-- <td id="home" width="10%">--> <!--<a href="./" title="Home"><img src="sites/default/themes/linuxjournal/logo.png" alt="Home" width="144" height="63" border="0" /></a>--> <!--</td>--> <!--<td id="site-info" width="20%">--> <!--</td>--> <td class="primary-links" width="70%" align="center" valign="middle"> <table id="primary-links-table" summary="Primary navigation elements." border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td id="home" rowspan="2"><a href="./" title="Home">
<img src="/sites/default/themes/linuxjournal/ljlogo.png" alt="Home"
border="0" /></a></td>
<td></td>
<td id="primary-links-hdr">Subscribe <strong>Now</strong></td>
</tr>
<tr>
<td id="tagline" valign="bottom" align="left">Since 1994:
The Original Monthly Magazine of the Linux Community</td>
<td id="primary-links" valign="middle">
<ul class="subscribeBar">
<li><a href="/xstatic/subs/">Subscribe</a></li>
<li><a href="https://www.ssc.com/dlissc/index">Renew</a></li>
<li><a href="/xstatic/subs/customer_service.html">Customer Service</a></li>
</ul>
</td>
</tr>
</table> </td> </tr></table><table id="secondary-menu" summary="Navigation elements." border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <td class="secondary-links" width="100%" align="center" valign="middle"> <table id="secondary-links-table" summary="Navigation elements." border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td id="secondary-links">
<table align="center"><tr>
<td width="18%"> </td>
<td align="center" width="16%"><a class="first" href="/xstatic/magazine">Magazine</a></td>
<td align="center" width="16%"><a class="second" href="/xstatic/advertising">Advertise</a></td>
<td align="center" width="16%"><a class="second" href="/xstatic/community">Community</a></td>
<td align="center" width="16%"><a class="second" href="/xstatic/aboutus">About Us</a></td>
<td width="18%"> </td>
</tr></table>
</td>
</tr>
</table> </td> <td width="25%" align="center" valign="middle"> <!-- <form action="search" method="GET"> <div id="search"> <input class="form-text" type="text" size="15" value="" name="keys" alt="Enter the terms you wish to search for." /> <input class="form-submit" type="submit" value="Search" alt="submit" /> </div> </form> --> </td> </tr></table><table id="content" border="0" cellpadding="15" cellspacing="0" width="100%"> <tr> <td id="sidebar-left"> <div class="block block-statistics" id="block-statistics-0"> <div class="title"><h3>Popular content</h3></div> <div class="content"><div class="item-list"><h3>Today's:</h3><ul><li><a href="node/1000081">3D Xgl Compiz Eye Candy for Ubuntu/Kubuntu Dapper and NVidia</a></li><li><a href="node/1000083">extendedPDF: Professional PDF controls for OpenOffice.org</a></li><li><a href="node/1000097">Microsoft's Masterpiece of FUD</a></li></ul></div><br /><div class="item-list"><h3>All time:</h3><ul><li><a href="article/3882">Why Python?</a></li><li><a href="article/5644">GNU/Linux DVD Player Review</a></li><li><a href="article/6011">Industrial Light & Magic</a></li></ul></div></div> </div> <div class="block block-block" id="block-block-30"> <div class="title"><h3>LJ Categories</h3></div> <div class="content"><p><a href="/xstatic/categories/categories">LJ Categories</a></p></div> </div> <div class="block block-block" id="block-block-2"> <div class="title"><h3>Free eNewsletters</h3></div> <div class="content"><table><tr><td><ul><li><a href="/xstatic/community/ljweeklyupdate">LJ Weekly Update</a></li><li><a href="/xstatic/community/suitwatch">Searls' Suitwatch</a></li><li><a href="/xstatic/community/tux-newsletter">TUX Desktop Watch</a></li></ul></td></tr></table></div> </div> <div class="block block-block" id="block-block-16"> <div class="title"><h3>LJ Merchandise</h3></div> <div class="content"><div><ul><!--<li><a class="enews" href="https://www.ssc.com/cgi-bin/lj/back_issue">Backissues</a></li><li><a class="enews" href="https://www.ssc.com/cgi-bin/lj/back_issue">Archive CD-ROM</a></li>--><li><a class="enews" href="http://www.cafepress.com/linuxjournal">T-shirts, mugs & more</a></li></ul></div></div> </div> <div class="block block-user" id="block-user-1"> <div class="title"><h3>Navigation</h3></div> <div class="content"><div class="menu"><ul><li class="leaf"><a href="tracker">recent posts</a></li><li class="collapsed"><a href="aggregator">news aggregator</a></li></ul></div></div> </div> </td> <td valign="top"> <div id="main"> <div class="breadcrumb"><a href="">Home</a></div> <h1 class="title">Memory Leak Detection in Embedded Systems</h1> <!-- begin content --> <div class="node "> <span class="submitted">By <a href="user/801087" title="View user profile.">Cal Erickson</a> on Sun, 2002-09-01 01:00.</span> <span class="taxonomy"><a href="taxonomy/term/5">Embedded</a></span> <div class="content"><p style="color:red"></p>Cal discusses mtrace, dmalloc and memwatch--three easy-to-use tools that find most application program errors.<div class="article" lang="en"><div class="simplesect" lang="en"><div class="titlepage"><h2 class="title"><a name="N0x850ca10.0x8573a54"></a></h2></div><p>One of the problems with developing embedded systems is the detection of memory leaks; I've found threetools that are useful for this. These tools are used to detect application program errors, not kernel memoryleaks. Two of these tools (mtrace and dmalloc) are part of the MontaVista Linux Professional Edition 2.1product. The other (memwatch) is available from the Web (see Resources).</p><p>C and C++ programmers control dynamic memory allocation. Reckless use of this control can lead to memorymanagement problems, which cause performance degradation, unpredictable execution or crashes.</p><p>Some of the problems that cause memory leaks are writing or reading beyond an allocated memory segment ortrying to free memory that has already been freed. A memory leak occurs when memory is allocated and notfreed after use, or when the pointer to a memory allocation is deleted, rendering the memory no longerusable. Memory leaks degrade performance due to increased paging, and over time, cause a program to run outof memory and crash. Access errors lead to data corruption, which causes a program to behave incorrectly orcrash. When a program runs out of memory it also can cause the Linux kernel to crash.</p><p>Designing and programming an embedded application requires great care. The application must be robustenough to handle every possible error that can occur; care should be taken to anticipate these errors andhandle them accordingly--especially in the area of memory. Often an application can run for some time beforeit mysteriously crashes itself or the system as a result of a memory allocation that is never freed. Findingthese errors can be done through use of memory leak detectors.</p><p>These tools work by replacing malloc, free and other memory management calls. Each tool has code thatintercepts calls to malloc (and other functions) and sets up tracking information for each memory request.Some tools implement memory protection fences to catch errant memory accesses.</p><p>Some of the leak detection programs are very large and require a virtual memory image of the program beingsearched. This requirement makes it very difficult to use on embedded systems. However, mtrace, memwatch anddmalloc are simple programs that find most errors.</p><p>All three tools were run on one example C program containing common memory handling errors. This program,together with Makefiles for building it with the three tools, is available as a downloadable file at <a href="ftp://ftp.ssc.com/pub/lj/listings/issue101/6059.tgz" target="_top">ftp.ssc.com/pub/lj/listings/issue101/6059.tgz</a>. All of these tools have been used in severaldifferent target architectures. The example code will work whether compiled natively or cross-compiled.</p></div><div class="simplesect" lang="en"><div class="titlepage"><h2 class="title"><a name="N0x850ca10.0x8573c0c"></a>mtrace</h2></div><p>The simplest of the three tools is mtrace. A feature of the GNU C library, mtrace allows detection ofmemory leaks caused by unbalanced malloc/free calls. It is implemented as a function call, mtrace(), whichturns on tracing and creates a log file of addresses malloc'd and freed. A Perl script, also called mtrace,displays the log file, listing only the unbalanced combinations and--if the source file is available-- theline number of the source where the malloc occurred. The tool can be used to check both C and C++ programsunder Linux. One of the features that makes mtrace desirable is the fact that it is scalable. It can be usedto do overall program debugging but can be scaled to work on a module basis as well.</p><p>Key to the use of the mtrace feature are three items: include mcheck.h, set the MALLOC_TRACE environmentvariable and call the mtrace() function call. If the MALLOC_TRACE variable is not set, mtrace() doesnothing.</p><p>The output of mtrace includes messages such as:</p><pre class="programlisting"><tt>- 0x0804a0f8 Free 13 was never alloc'd/memory_leak/memory_leaks/mtrace/my_test.c:193</tt></pre><p>to indicate memory that was freed but never malloc'd and a ``Memory not freed'' section that includes theaddress, size and line number of calls to malloc for which no free occurred.</p></div><div class="simplesect" lang="en"><div class="titlepage"><h2 class="title"><a name="N0x850ca10.0x8573d40"></a>memwatch</h2></div><p><span class="bold"><b>memwatch</b></span> is a program that not only detects malloc and free errors butalso fencepost conditions. Fencepost conditions occur when writing data into an allocated chunk of memory(allocated by malloc) and the data goes beyond the end of the allocated area. Some things that memwatch doesnot catch are writing to an address that has been freed and reading data from outside the allocatedmemory.</p><p>The heart of memwatch is the memwatch.c file. It implements the wrappers and code for the addresschecking. To use memwatch the file memwatch.h must be included in the source. The variables MEMWATCH andMW_STDIO must be defined on the compile command line (-DMEMWATCH and -DMW_STDIO). The memwatch.c file must beused with the application as well. The object module from the compile of memwatch.c must be included in thelink of the application. Upon execution of the application, a message will appear on stdout if memwatch foundany abnormalities. The file memwatch.log is created that contains the information about the errorsencountered. Each error message contains the line number and source-code filename where the erroroccurred.</p><p>Comparing memwatch.log with the log from mtrace, the same errors are reported. The memwatch tool alsofound a fencepost condition where the memory addresses were changed to overwrite the start and end of anallocated area, showing the expanded capability of memwatch in this case. The disadvantage is that memwatchis not scalable. It has to run on the whole application.</p></div><div class="simplesect" lang="en"><div class="titlepage"><h2 class="title"><a name="N0x850ca10.0x8573e48"></a>dmalloc</h2></div><p>The third tool is a library that is designed as a drop-in substitute for malloc, realloc, calloc, free andother memory management functions. It provides runtime configurability. The features of the tool providememory leak tracing and fencepost write detection. It reports its errors by filename and line number and logssome general statistics. This library, created and maintained by Gray Watson, has been ported to manyoperating systems other than Linux.</p><p>The package is configurable to include thread support and C++ support. It can be built both as shared andstatic libraries. All of these options are selected when building the tool. The result is a set of librariesthat are used when linking the application program. There is an include file (dmalloc.h) that needs to beincluded in the source of the application to be checked. In addition to the library and include file, it isnecessary to have an environment variable set up that dmalloc reads to configure how it checks and where itputs the logging information. The following line is the setup used with the test program for dmalloc:</p><pre class="programlisting"><tt>export \DMALLOC_OPTIONS=debug=0x44a40503,inter=1,log=logfile</tt></pre><p>What this means is 1) log is a file named logfile in the current directory, 2) inter is the frequency forthe library to check itself and 3) debug is a hex number whose bits select the types of checking to do. Thisexample tests for just about every possible error. The following is a list of the tests and the correspondingbits to set in ``debug'':</p><div class="itemizedlist"><ul type="disc"><li><p>none (nil): no functionality (0)</p></li><li><p>log-stats (lst): log general statistics (0x1)</p></li><li><p>log-non-free (lnf): log non-freed pointers (0x2)</p></li><li><p>log-known (lkn): log only known non-freed (0x4)</p></li><li><p>log-trans (ltr): log memory transactions (0x8)</p></li><li><p>log-admin (lad): log administrative info (0x20)</p></li><li><p>log-blocks (lbl): log blocks when heap-map (0x40)</p></li><li><p>log-bad-space (lbs): dump space from bad pointers (0x100)</p></li><li><p>log-nonfree-space (lns): dump space from non-freed pointers (0x200)</p></li><li><p>log-elapsed-time (let): log elapsed time for allocated pointer (0x40000)</p></li><li><p>log-current-time (lct): log current time for allocated pointer (0x80000)</p></li><li><p>check-fence (cfe): check fencepost errors (0x400)</p></li><li><p>check-heap (che): check heap adm structs (0x800)</p></li><li><p>check-lists (cli): check free lists (0x1000)</p></li><li><p>check-blank (cbl): check mem overwritten by alloc-blank, free-blank (0x2000)</p></li>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -