Merge pull request #3621 from soooogreen/master

[done]
This commit is contained in:
VicYu 2015-12-14 02:16:28 +08:00
commit b9723c694b
2 changed files with 299 additions and 285 deletions

View File

@ -1,285 +0,0 @@
translating。。。
Review: 5 memory debuggers for Linux coding
================================================================================
![](http://images.techhive.com/images/article/2015/11/penguinadmin-2400px-100627186-primary.idge.jpg)
Credit: [Moini][1]
As a programmer, I'm aware that I tend to make mistakes -- and why not? Even programmers are human. Some errors are detected during code compilation, while others get caught during software testing. However, a category of error exists that usually does not get detected at either of these stages and that may cause the software to behave unexpectedly -- or worse, terminate prematurely.
If you haven't already guessed it, I am talking about memory-related errors. Manually debugging these errors can be not only time-consuming but difficult to find and correct. Also, it's worth mentioning that these errors are surprisingly common, especially in software written in programming languages like C and C++, which were designed for use with [manual memory management][2].
Thankfully, several programming tools exist that can help you find memory errors in your software programs. In this roundup, I assess five popular, free and open-source memory debuggers that are available for Linux: Dmalloc, Electric Fence, Memcheck, Memwatch and Mtrace. I've used all five in my day-to-day programming, and so these reviews are based on practical experience.
eviews are based on practical experience.
### [Dmalloc][3] ###
**Developer**: Gray Watson
**Reviewed version**: 5.5.2
**Linux support**: All flavors
**License**: Creative Commons Attribution-Share Alike 3.0 License
Dmalloc is a memory-debugging tool developed by Gray Watson. It is implemented as a library that provides wrappers around standard memory management functions like **malloc(), calloc(), free()** and more, enabling programmers to detect problematic code.
![cw dmalloc output](http://images.techhive.com/images/article/2015/11/cw_dmalloc-output-100627040-large.idge.png)
Dmalloc
As listed on the tool's Web page, the debugging features it provides includes memory-leak tracking, [double free][4] error tracking and [fence-post write detection][5]. Other features include file/line number reporting, and general logging of statistics.
#### What's new ####
Version 5.5.2 is primarily a [bug-fix release][6] containing corrections for a couple of build and install problems.
#### What's good about it ####
The best part about Dmalloc is that it's extremely configurable. For example, you can configure it to include support for C++ programs as well as threaded applications. A useful functionality it provides is runtime configurability, which means that you can easily enable/disable the features the tool provides while it is being executed.
You can also use Dmalloc with the [GNU Project Debugger (GDB)][7] -- just add the contents of the dmalloc.gdb file (located in the contrib subdirectory in Dmalloc's source package) to the .gdbinit file in your home directory.
Another thing that I really like about Dmalloc is its extensive documentation. Just head to the [documentation section][8] on its official website, and you'll get everything from how to download, install, run and use the library to detailed descriptions of the features it provides and an explanation of the output file it produces. There's also a section containing solutions to some common problems.
#### Other considerations ####
Like Mtrace, Dmalloc requires programmers to make changes to their program's source code. In this case you may, at the very least, want to add the **dmalloc.h** header, because it allows the tool to report the file/line numbers of calls that generate problems, something that is very useful as it saves time while debugging.
In addition, the Dmalloc library, which is produced after the package is compiled, needs to be linked with your program while the program is being compiled.
However, complicating things somewhat is the fact that you also need to set an environment variable, dubbed **DMALLOC_OPTION**, that the debugging tool uses to configure the memory debugging features -- as well as the location of the output file -- at runtime. While you can manually assign a value to the environment variable, beginners may find that process a bit tough, given that the Dmalloc features you want to enable are listed as part of that value, and are actually represented as a sum of their respective hexadecimal values -- you can read more about it [here][9].
An easier way to set the environment variable is to use the [Dmalloc Utility Program][10], which was designed for just that purpose.
#### Bottom line ####
Dmalloc's real strength lies in the configurability options it provides. It is also highly portable, having being successfully ported to many OSes, including AIX, BSD/OS, DG/UX, Free/Net/OpenBSD, GNU/Hurd, HPUX, Irix, Linux, MS-DOG, NeXT, OSF, SCO, Solaris, SunOS, Ultrix, Unixware and even Unicos (on a Cray T3E). Although the tool has a bit of a learning curve associated with it, the features it provides are worth it.
### [Electric Fence][15] ###
**Developer**: Bruce Perens
**Reviewed version**: 2.2.3
**Linux support**: All flavors
**License**: GNU GPL (version 2)
Electric Fence is a memory-debugging tool developed by Bruce Perens. It is implemented in the form of a library that your program needs to link to, and is capable of detecting overruns of memory allocated on a [heap][11] ) as well as memory accesses that have already been released.
![cw electric fence output](http://images.techhive.com/images/article/2015/11/cw_electric-fence-output-100627041-large.idge.png)
Electric Fence
As the name suggests, Electric Fence creates a virtual fence around each allocated buffer in a way that any illegal memory access results in a [segmentation fault][12]. The tool supports both C and C++ programs.
#### What's new ####
Version 2.2.3 contains a fix for the tool's build system, allowing it to actually pass the -fno-builtin-malloc option to the [GNU Compiler Collection (GCC)][13].
#### What's good about it ####
The first thing that I liked about Electric Fence is that -- unlike Memwatch, Dmalloc and Mtrace -- it doesn't require you to make any changes in the source code of your program. You just need to link your program with the tool's library during compilation.
Secondly, the way the debugging tool is implemented makes sure that a segmentation fault is generated on the very first instruction that causes a bounds violation, which is always better than having the problem detected at a later stage.
Electric Fence always produces a copyright message in output irrespective of whether an error was detected or not. This behavior is quite useful, as it also acts as a confirmation that you are actually running an Electric Fence-enabled version of your program.
#### Other considerations ####
On the other hand, what I really miss in Electric Fence is the ability to detect memory leaks, as it is one of the most common and potentially serious problems that software written in C/C++ has. In addition, the tool cannot detect overruns of memory allocated on the stack, and is not thread-safe.
Given that the tool allocates an inaccessible virtual memory page both before and after a user-allocated memory buffer, it ends up consuming a lot of extra memory if your program makes too many dynamic memory allocations.
Another limitation of the tool is that it cannot explicitly tell exactly where the problem lies in your programs' code -- all it does is produce a segmentation fault whenever it detects a memory-related error. To find out the exact line number, you'll have to debug your Electric Fence-enabled program with a tool like [The Gnu Project Debugger (GDB)][14], which in turn depends on the -g compiler option to produce line numbers in output.
Finally, although Electric Fence is capable of detecting most buffer overruns, an exception is the scenario where the allocated buffer size is not a multiple of the word size of the system -- in that case, an overrun (even if it's only a few bytes) won't be detected.
#### Bottom line ####
Despite all its limitations, where Electric Fence scores is the ease of use -- just link your program with the tool once, and it'll alert you every time it detects a memory issue it's capable of detecting. However, as already mentioned, the tool requires you to use a source-code debugger like GDB.
### [Memcheck][16] ###
**Developer**: [Valgrind Developers][17]
**Reviewed version**: 3.10.1
**Linux support**: All flavors
**License**: GPL
[Valgrind][18] is a suite that provides several tools for debugging and profiling Linux programs. Although it works with programs written in many different languages -- such as Java, Perl, Python, Assembly code, Fortran, Ada and more -- the tools it provides are largely aimed at programs written in C and C++.
The most popular Valgrind tool is Memcheck, a memory-error detector that can detect issues such as memory leaks, invalid memory access, uses of undefined values and problems related to allocation and deallocation of heap memory.
#### What's new ####
This [release][19] of the suite (3.10.1) is a minor one that primarily contains fixes to bugs reported in version 3.10.0. In addition, it also "backports fixes for all reported missing AArch64 ARMv8 instructions and syscalls from the trunk."
#### What's good about it ####
Memcheck, like all other Valgrind tools, is basically a command line utility. It's very easy to use: If you normally run your program on the command line in a form such as prog arg1 arg2, you just need to add a few values, like this: valgrind --leak-check=full prog arg1 arg2.
![cw memcheck output](http://images.techhive.com/images/article/2015/11/cw_memcheck-output-100627037-large.idge.png)
Memcheck
(Note: You don't need to mention Memcheck anywhere in the command line because it's the default Valgrind tool. However, you do need to initially compile your program with the -g option -- which adds debugging information -- so that Memcheck's error messages include exact line numbers.)
What I really like about Memcheck is that it provides a lot of command line options (such as the --leak-check option mentioned above), allowing you to not only control how the tool works but also how it produces the output.
For example, you can enable the --track-origins option to see information on the sources of uninitialized data in your program. Enabling the --show-mismatched-frees option will let Memcheck match the memory allocation and deallocation techniques. For code written in C language, Memcheck will make sure that only the free() function is used to deallocate memory allocated by malloc(), while for code written in C++, the tool will check whether or not the delete and delete[] operators are used to deallocate memory allocated by new and new[], respectively. If a mismatch is detected, an error is reported.
But the best part, especially for beginners, is that the tool even produces suggestions about which command line option the user should use to make the output more meaningful. For example, if you do not use the basic --leak-check option, it will produce an output suggesting: "Rerun with --leak-check=full to see details of leaked memory." And if there are uninitialized variables in the program, the tool will generate a message that says, "Use --track-origins=yes to see where uninitialized values come from."
Another useful feature of Memcheck is that it lets you [create suppression files][20], allowing you to suppress certain errors that you can't fix at the moment -- this way you won't be reminded of them every time the tool is run. It's worth mentioning that there already exists a default suppression file that Memcheck reads to suppress errors in the system libraries, such as the C library, that come pre-installed with your OS. You can either create a new suppression file for your use, or edit the existing one (usually /usr/lib/valgrind/default.supp).
For those seeking advanced functionality, it's worth knowing that Memcheck can also [detect memory errors][21] in programs that use [custom memory allocators][22]. In addition, it also provides [monitor commands][23] that can be used while working with Valgrind's built-in gdbserver, as well as a [client request mechanism][24] that allows you not only to tell the tool facts about the behavior of your program, but make queries as well.
#### Other considerations ####
While there's no denying that Memcheck can save you a lot of debugging time and frustration, the tool uses a lot of memory, and so can make your program execution significantly slower (around 20 to 30 times, [according to the documentation][25]).
Aside from this, there are some other limitations, too. According to some user comments, Memcheck apparently isn't [thread-safe][26]; it doesn't detect [static buffer overruns][27]). Also, there are some Linux programs, like [GNU Emacs][28], that currently do not work with Memcheck.
If you're interested in taking a look, an exhaustive list of Valgrind's limitations can be found [here][29].
#### Bottom line ####
Memcheck is a handy memory-debugging tool for both beginners as well as those looking for advanced features. While it's very easy to use if all you need is basic debugging and error checking, there's a bit of learning curve if you want to use features like suppression files or monitor commands.
Although it has a long list of limitations, Valgrind (and hence Memcheck) claims on its site that it is used by [thousands of programmers][30] across the world -- the team behind the tool says it's received feedback from users in over 30 countries, with some of them working on projects with up to a whopping 25 million lines of code.
### [Memwatch][31] ###
**Developer**: Johan Lindh
**Reviewed version**: 2.71
**Linux support**: All flavors
**License**: GNU GPL
Memwatch is a memory-debugging tool developed by Johan Lindh. Although it's primarily a memory-leak detector, it is also capable (according to its Web page) of detecting other memory-related issues like [double-free error tracking and erroneous frees][32], buffer overflow and underflow, [wild pointer][33] writes, and more.
The tool works with programs written in C. Although you can also use it with C++ programs, it's not recommended (according to the Q&A file that comes with the tool's source package).
#### What's new ####
This version adds ULONG_LONG_MAX to detect whether a program is 32-bit or 64-bit.
#### What's good about it ####
Like Dmalloc, Memwatch comes with good documentation. You can refer to the USING file if you want to learn things like how the tool works; how it performs initialization, cleanup and I/O operations; and more. Then there is a FAQ file that is aimed at helping users in case they face any common error while using Memcheck. Finally, there is a test.c file that contains a working example of the tool for your reference.
![cw memwatch output](http://images.techhive.com/images/article/2015/11/cw_memwatch_output-100627038-large.idge.png)
Memwatch
Unlike Mtrace, the log file to which Memwatch writes the output (usually memwatch.log) is in human-readable form. Also, instead of truncating, Memwatch appends the memory-debugging output to the file each time the tool is run, allowing you to easily refer to the previous outputs should the need arise.
It's also worth mentioning that when you execute your program with Memwatch enabled, the tool produces a one-line output on [stdout][34] informing you that some errors were found -- you can then head to the log file for details. If no such error message is produced, you can rest assured that the log file won't contain any mistakes -- this actually saves time if you're running the tool several times.
Another thing that I liked about Memwatch is that it also provides a way through which you can capture the tool's output from within the code, and handle it the way you like (refer to the mwSetOutFunc() function in the Memwatch source code for more on this).
#### Other considerations ####
Like Mtrace and Dmalloc, Memwatch requires you to add extra code to your source file -- you have to include the memwatch.h header file in your code. Also, while compiling your program, you need to either compile memwatch.c along with your program's source files or include the object module from the compile of the file, as well as define the MEMWATCH and MW_STDIO variables on the command line. Needless to say, the -g compiler option is also required for your program if you want exact line numbers in the output.
There are some features that it doesn't contain. For example, the tool cannot detect attempts to write to an address that has already been freed or read data from outside the allocated memory. Also, it's not thread-safe. Finally, as I've already pointed out in the beginning, there is no guarantee on how the tool will behave if you use it with programs written in C++.
#### Bottom line ####
Memcheck can detect many memory-related problems, making it a handy debugging tool when dealing with projects written in C. Given that it has a very small source code, you can learn how the tool works, debug it if the need arises, and even extend or update its functionality as per your requirements.
### [Mtrace][35] ###
**Developers**: Roland McGrath and Ulrich Drepper
**Reviewed version**: 2.21
**Linux support**: All flavors
**License**: GNU LGPL
Mtrace is a memory-debugging tool included in [the GNU C library][36]. It works with both C and C++ programs on Linux, and detects memory leaks caused by unbalanced calls to the malloc() and free() functions.
![cw mtrace output](http://images.techhive.com/images/article/2015/11/cw_mtrace-output-100627039-large.idge.png)
Mtrace
The tool is implemented in the form of a function called mtrace(), which traces all malloc/free calls made by a program and logs the information in a user-specified file. Because the file contains data in computer-readable format, a Perl script -- also named mtrace -- is used to convert and display it in human-readable form.
#### What's new ####
[The Mtrace source][37] and [the Perl file][38] that now come with the GNU C library (version 2.21) add nothing new to the tool aside from an update to the copyright dates.
#### What's good about it ####
The best part about Mtrace is that the learning curve for it isn't steep; all you need to understand is how and where to add the mtrace() -- and the corresponding muntrace() -- function in your code, and how to use the Mtrace Perl script. The latter is very straightforward -- all you have to do is run the mtrace() <program-executable> <log-file-generated-upon-program-execution> command. (For an example, see the last command in the screenshot above.)
Another thing that I like about Mtrace is that it's scalable -- which means that you can not only use it to debug a complete program, but can also use it to detect memory leaks in individual modules of the program. Just call the mtrace() and muntrace() functions within each module.
Finally, since the tool is triggered when the mtrace() function -- which you add in your program's source code -- is executed, you have the flexibility to enable the tool dynamically (during program execution) [using signals][39].
#### Other considerations ####
Because the calls to mtrace() and mauntrace() functions -- which are declared in the mcheck.h file that you need to include in your program's source -- are fundamental to Mtrace's operation (the mauntrace() function is not [always required][40]), the tool requires programmers to make changes in their code at least once.
Be aware that you need to compile your program with the -g option (provided by both the [GCC][41] and [G++][42] compilers), which enables the debugging tool to display exact line numbers in the output. In addition, some programs (depending on how big their source code is) can take a long time to compile. Finally, compiling with -g increases the size of the executable (because it produces extra information for debugging), so you have to remember that the program needs to be recompiled without -g after the testing has been completed.
To use Mtrace, you need to have some basic knowledge of environment variables in Linux, given that the path to the user-specified file -- which the mtrace() function uses to log all the information -- has to be set as a value for the MALLOC_TRACE environment variable before the program is executed.
Feature-wise, Mtrace is limited to detecting memory leaks and attempts to free up memory that was never allocated. It can't detect other memory-related issues such as illegal memory access or use of uninitialized memory. Also, [there have been complaints][43] that it's not [thread-safe][44].
### Conclusions ###
Needless to say, each memory debugger that I've discussed here has its own qualities and limitations. So, which one is best suited for you mostly depends on what features you require, although ease of setup and use might also be a deciding factor in some cases.
Mtrace is best suited for cases where you just want to catch memory leaks in your software program. It can save you some time, too, since the tool comes pre-installed on your Linux system, something which is also helpful in situations where the development machines aren't connected to the Internet or you aren't allowed to download a third party tool for any kind of debugging.
Dmalloc, on the other hand, can not only detect more error types compared to Mtrace, but also provides more features, such as runtime configurability and GDB integration. Also, unlike any other tool discussed here, Dmalloc is thread-safe. Not to mention that it comes with detailed documentation, making it ideal for beginners.
Although Memwatch comes with even more comprehensive documentation than Dmalloc, and can detect even more error types, you can only use it with software written in the C programming language. One of its features that stands out is that it lets you handle its output from within the code of your program, something that is helpful in case you want to customize the format of the output.
If making changes to your program's source code is not what you want, you can use Electric Fence. However, keep in mind that it can only detect a couple of error types, and that doesn't include memory leaks. Plus, you also need to know GDB basics to make the most out of this memory-debugging tool.
Memcheck is probably the most comprehensive of them all. It detects more error types and provides more features than any other tool discussed here -- and it doesn't require you to make any changes in your program's source code.But be aware that, while the learning curve is not very high for basic usage, if you want to use its advanced features, a level of expertise is definitely required.
--------------------------------------------------------------------------------
via: http://www.computerworld.com/article/3003957/linux/review-5-memory-debuggers-for-linux-coding.html
作者:[Himanshu Arora][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:http://www.computerworld.com/author/Himanshu-Arora/
[1]:https://openclipart.org/detail/132427/penguin-admin
[2]:https://en.wikipedia.org/wiki/Manual_memory_management
[3]:http://dmalloc.com/
[4]:https://www.owasp.org/index.php/Double_Free
[5]:https://stuff.mit.edu/afs/sipb/project/gnucash-test/src/dmalloc-4.8.2/dmalloc.html#Fence-Post%20Overruns
[6]:http://dmalloc.com/releases/notes/dmalloc-5.5.2.html
[7]:http://www.gnu.org/software/gdb/
[8]:http://dmalloc.com/docs/
[9]:http://dmalloc.com/docs/latest/online/dmalloc_26.html#SEC32
[10]:http://dmalloc.com/docs/latest/online/dmalloc_23.html#SEC29
[11]:https://en.wikipedia.org/wiki/Memory_management#Dynamic_memory_allocation
[12]:https://en.wikipedia.org/wiki/Segmentation_fault
[13]:https://en.wikipedia.org/wiki/GNU_Compiler_Collection
[14]:http://www.gnu.org/software/gdb/
[15]:https://launchpad.net/ubuntu/+source/electric-fence/2.2.3
[16]:http://valgrind.org/docs/manual/mc-manual.html
[17]:http://valgrind.org/info/developers.html
[18]:http://valgrind.org/
[19]:http://valgrind.org/docs/manual/dist.news.html
[20]:http://valgrind.org/docs/manual/mc-manual.html#mc-manual.suppfiles
[21]:http://valgrind.org/docs/manual/mc-manual.html#mc-manual.mempools
[22]:http://stackoverflow.com/questions/4642671/c-memory-allocators
[23]:http://valgrind.org/docs/manual/mc-manual.html#mc-manual.monitor-commands
[24]:http://valgrind.org/docs/manual/mc-manual.html#mc-manual.clientreqs
[25]:http://valgrind.org/docs/manual/valgrind_manual.pdf
[26]:http://sourceforge.net/p/valgrind/mailman/message/30292453/
[27]:https://msdn.microsoft.com/en-us/library/ee798431%28v=cs.20%29.aspx
[28]:http://www.computerworld.com/article/2484425/linux/5-free-linux-text-editors-for-programming-and-word-processing.html?nsdr=true&page=2
[29]:http://valgrind.org/docs/manual/manual-core.html#manual-core.limits
[30]:http://valgrind.org/info/
[31]:http://www.linkdata.se/sourcecode/memwatch/
[32]:http://www.cecalc.ula.ve/documentacion/tutoriales/WorkshopDebugger/007-2579-007/sgi_html/ch09.html
[33]:http://c2.com/cgi/wiki?WildPointer
[34]:https://en.wikipedia.org/wiki/Standard_streams#Standard_output_.28stdout.29
[35]:http://www.gnu.org/software/libc/manual/html_node/Tracing-malloc.html
[36]:https://www.gnu.org/software/libc/
[37]:https://sourceware.org/git/?p=glibc.git;a=history;f=malloc/mtrace.c;h=df10128b872b4adc4086cf74e5d965c1c11d35d2;hb=HEAD
[38]:https://sourceware.org/git/?p=glibc.git;a=history;f=malloc/mtrace.pl;h=0737890510e9837f26ebee2ba36c9058affb0bf1;hb=HEAD
[39]:http://webcache.googleusercontent.com/search?q=cache:s6ywlLtkSqQJ:www.gnu.org/s/libc/manual/html_node/Tips-for-the-Memory-Debugger.html+&cd=1&hl=en&ct=clnk&gl=in&client=Ubuntu
[40]:http://www.gnu.org/software/libc/manual/html_node/Using-the-Memory-Debugger.html#Using-the-Memory-Debugger
[41]:http://linux.die.net/man/1/gcc
[42]:http://linux.die.net/man/1/g++
[43]:https://sourceware.org/ml/libc-help/2014-05/msg00008.html
[44]:https://en.wikipedia.org/wiki/Thread_safety

View File

@ -0,0 +1,299 @@
点评Linux编程中五款内存调试器
================================================================================
![](http://images.techhive.com/images/article/2015/11/penguinadmin-2400px-100627186-primary.idge.jpg)
Credit: [Moini][1]
作为一个程序员,我知道我总在犯错误——事实是,怎么可能会不犯错的!程序员也是人啊。有的错误能在编码过程中及时发现,而有些却得等到软件测试才显露出来。然而,有一类错误并不能在这两个时期被排除,从而导致软件不能正常运行,甚至是提前中止。
想到了吗我说的就是内存相关的错误。手动调试这些错误不仅耗时而且很难发现并纠正。值得一提的是这种错误非常地常见特别是在一些软件里这些软件是用C/C++这类允许[手动管理内存][2]的语言编写的。
幸运的是现行有一些编程工具能够帮你找到软件程序中这些内存相关的错误。在这些工具集中我评定了五款Linux可用的流行、免费并且开源的内存调试器Dmalloc、Electric Fence、 Memcheck、 Memwatch以及Mtrace。日常编码过程中我已经把这五个调试器用了个遍所以这些点评是建立在我的实际体验之上的。
### [Dmalloc][3] ###
**开发者**Gray Watson
**点评版本**5.5.2
**Linux支持**:所有种类
**许可**:知识共享署名-相同方式共享许可证3.0
Dmalloc是Gray Watson开发的一款内存调试工具。它实现成库封装了标准内存管理函数如**malloc(), calloc(), free()**等,使得程序员得以检测出有问题的代码。
![cw dmalloc output](http://images.techhive.com/images/article/2015/11/cw_dmalloc-output-100627040-large.idge.png)
Dmalloc
如同工具的网页所列,这个调试器提供的特性包括内存泄漏跟踪、[重复释放(double free)][4]错误跟踪、以及[越界写入(fence-post write)][5]检测。其它特性包括文件/行号报告、普通统计记录。
#### 更新内容 ####
5.5.2版本是一个[bug修复发行版][6],同时修复了构建和安装的问题。
#### 有何优点 ####
Dmalloc最大的优点是可以进行任意配置。比如说你可以配置以支持C++程序和多线程应用。Dmalloc还提供一个有用的功能运行时可配置这表示在Dmalloc执行时可以轻易地使能或者禁能它提供的特性。
你还可以配合[GNU Project Debugger (GDB)][7]来使用Dmalloc只需要将dmalloc.gdb文件位于Dmalloc源码包中的contrib子目录里的内容添加到你的主目录中的.gdbinit文件里即可。
另外一个优点让我对Dmalloc爱不释手的是它有大量的资料文献。前往官网的[Documentation标签][8]可以获取任何内容有关于如何下载、安装、运行怎样使用库和Dmalloc所提供特性的细节描述及其输入文件的解释。里面还有一个章节介绍了一般问题的解决方法。
#### 注意事项 ####
跟Mtrace一样Dmalloc需要程序员改动他们的源代码。比如说你可以必须的添加头文件**dmalloc.h**,工具就能汇报产生问题的调用的文件或行号。这个功能非常有用,因为它节省了调试的时间。
除此之外还需要在编译你的程序时把Dmalloc库编译源码包时产生的链接进去。
然而,还有点更麻烦的事,需要设置一个环境变量,命名为**DMALLOC_OPTION**以供工具在运行时配置内存调试特性以及输出文件的路径。可以手动为该环境变量分配一个值不过初学者可能会觉得这个过程有点困难因为你想使能的Dmalloc特性是存在于这个值之中的——表示为各自的十六进制值的累加。[这里][9]有详细介绍。
一个比较简单方法设置这个环境变量是使用[Dmalloc实用指令][10],这是专为这个目的设计的方法。
#### 总结 ####
Dmalloc真正的优势在于它的可配置选项。而且高度可移植曾经成功移植到多种操作系统如AIX、BSD/OS、DG/UX、Free/Net/OpenBSD、GNU/Hurd、HPUX、Irix、Linux、MS-DOG、NeXT、OSF、SCO、Solaris、SunOS、Ultrix、Unixware甚至Unicos运行在Cray T3E主机上。虽然Dmalloc有很多东西需要学习但是它所提供的特性值得为之付出。
### [Electric Fence][15] ###
**开发者**Bruce Perens
**点评版本**2.2.3
**Linux支持**:所有种类
**许可**GNU 通用公共许可证 (第二版)
Electric Fence是Bruce Perens开发的一款内存调试工具它以库的形式实现你的程序需要链接它。Electric Fence能检测出[栈][11]内存溢出和访问已经释放的内存。
![cw electric fence output](http://images.techhive.com/images/article/2015/11/cw_electric-fence-output-100627041-large.idge.png)
Electric Fence
顾名思义Electric Fence在每个申请的缓存边界建立了fence防护任何非法内存访问都会导致[段错误][12]。这个调试工具同时支持C和C++编程。
#### 更新内容 ####
2.2.3版本修复了工具的构建系统,使得-fno-builtin-malloc选项能真正传给[GNU Compiler Collection (GCC)][13]。
#### 有何优点 ####
我喜欢Electric Fence首要的一点是Memwatch、Dmalloc和Mtrace所不具有的这个调试工具不需要你的源码做任何的改动你只需要在编译的时候把它的库链接进你的程序即可。
其次Electric Fence实现一个方法确认导致越界访问(a bounds violation)的第一个指令就是引起段错误的原因。这比在后面再发现问题要好多了。
不管是否有检测出错误Electric Fence经常会在输出产生版权信息。这一点非常有用由此可以确定你所运行的程序已经启用了Electric Fence。
#### 注意事项 ####
另一方面我对Electric Fence真正念念不忘的是它检测内存泄漏的能力。内存泄漏是C/C++软件最常见也是最难隐秘的问题之一。不过Electric Fence不能检测出堆内存溢出而且也不是线程安全的。
基于Electric Fence会在用户分配内存区的前后分配禁止访问的虚拟内存页如果你过多的进行动态内存分配将会导致你的程序消耗大量的额外内存。
Electric Fence还有一个局限是不能明确指出错误代码所在的行号。它所能做只是在监测到内存相关错误时产生段错误。想要定位行号需要借助[The Gnu Project Debugger (GDB)][14]这样的调试工具来调试你启用了Electric Fence的程序。
最后一点Electric Fence虽然能检测出大部分的缓冲区溢出有一个例外是如果所申请的缓冲区大小不是系统字长的倍数这时候溢出即使只有几个字节就不能被检测出来。
#### 总结 ####
尽管有那么多的局限但是Electric Fence的优点却在于它的易用性。程序只要链接工具一次Electric Fence就可以在监测出内存相关问题的时候报警。不过如同前面所说Electric Fence需要配合像GDB这样的源码调试器使用。
### [Memcheck][16] ###
**开发者**[Valgrind开发团队][17]
**点评版本**3.10.1
**Linux支持**:所有种类
**许可**:通用公共许可证
[Valgrind][18]是一个提供好几款调试和Linux程序性能分析工具的套件。虽然Valgrind和编写语言各不相同有Java、Perl、Python、Assembly code、ortran、Ada等等的程序配合工作但是它所提供的工具大部分都意在支持C/C++所编写的程序。
Memcheck作为内存错误检测器是一款最受欢迎的Memcheck工具。它能够检测出诸多问题诸如内存泄漏、无效的内存访问、未定义变量的使用以及栈内存分配和释放相关的问题等。
#### 更新内容 ####
工具套件(3.10.1)的[发行版][19]是一个副版本主要修复了3.10.0版本发现的bug。除此之外从主版本backport一些包修复了缺失的AArch64 ARMv8指令和系统调用。
#### 有何优点 ####
同其它所有Valgrind工具一样Memcheck也是基本的命令行实用程序。它的操作非常简单通常我们会使用诸如prog arg1 arg2格式的命令来运行程序而Memcheck只要求你多加几个值即可就像valgrind --leak-check=full prog arg1 arg2。
![cw memcheck output](http://images.techhive.com/images/article/2015/11/cw_memcheck-output-100627037-large.idge.png)
Memcheck
注意因为Memcheck是Valgrind的默认工具所以无需提及Memcheck。但是需要在编译程序之初带上-g参数选项这一步会添加调试信息使得Memcheck的错误信息会包含正确的行号。
我真正倾心于Memcheck的是它提供了很多命令行选项如上所述的--leak-check选项如此不仅能控制工具运转还可以控制它的输出。
举个例子,可以开启--track-origins选项以查看程序源码中未初始化的数据。可以开启--show-mismatched-frees选项让Memcheck匹配内存的分配和释放技术。对于C语言所写的代码Memcheck会确保只能使用free()函数来释放内存malloc()函数来申请内存。而对C++所写的源码Memcheck会检查是否使用了delete或delete[]操作符来释放内存以及new或者new[]来申请内存。
Memcheck最好的特点尤其是对于初学者来说的是它会给用户建议使用那个命令行选项能让输出更加有意义。比如说如果你不使用基本的--leak-check选项Memcheck会在输出时建议“使用--leak-check=full重新运行查看更多泄漏内存细节”。如果程序有未初始化的变量Memcheck会产生信息“使用--track-origins=yes查看未初始化变量的定位”。
Memcheck另外一个有用的特性是它可以[创建抑制文件(suppression files)][20]由此可以忽略特定不能修正的错误这样Memcheck运行时就不会每次都报警了。值得一提的是Memcheck会去读取默认抑制文件来忽略系统库比如C库中的报错这些错误在系统创建之前就已经存在了。可以选择创建一个新的抑制文件或是编辑现有的(通常是/usr/lib/valgrind/default.supp)。
Memcheck还有高级功能比如可以使用[定制内存分配器][22]来[检测内存错误][21]。除此之外Memcheck提供[监控命令][23]当用到Valgrind的内置gdbserver以及[客户端请求][24]机制不仅能把程序的行为告知Memcheck还可以进行查询时可以使用。
#### 注意事项 ####
毫无疑问Memcheck可以节省很多调试时间以及省去很多麻烦。但是它使用了很多内存导致程序执行变慢[由资料可知][25]大概花上20至30倍时间
除此之外Memcheck还有其它局限。根据用户评论Memcheck明显不是[线程安全][26]的;它不能检测出 [静态缓冲区溢出][27]还有就是一些Linux程序如[GNU Emacs][28]目前还不能使用Memcheck。
如果有兴趣,可以在[这里][29]查看Valgrind详尽的局限性说明。
#### 总结 ####
无论是对于初学者还是那些需要高级特性的人来说Memcheck都是一款便捷的内存调试工具。如果你仅需要基本调试和错误核查Memcheck会非常容易上手。而当你想要使用像抑制文件或者监控指令这样的特性就需要花一些功夫学习了。
虽然罗列了大量的局限性但是Valgrind包括Memcheck在它的网站上声称全球有[成千上万程序员][30]使用了此工具。开发团队称收到来自超过30个国家的用户反馈而这些用户的工程代码有的高达2.5千万行。
### [Memwatch][31] ###
**开发者**Johan Lindh
**点评版本**2.71
**Linux支持**:所有种类
**许可**GNU通用公共许可证
Memwatch是由Johan Lindh开发的内存调试工具虽然它主要扮演内存泄漏检测器的角色但是它也具有检测其它如[重复释放跟踪和内存错误释放][32]、缓冲区溢出和下溢、[野指针][33]写入等等内存相关问题的能力(根据网页介绍所知)。
Memwatch支持用C语言所编写的程序。可以在C++程序中使用它但是这种做法并不提倡由Memwatch源码包随附的Q&A文件中可知
#### 更新内容 ####
这个版本添加了ULONG_LONG_MAX以区分32位和64位程序。
#### 有何优点 ####
跟Dmalloc一样Memwatch也有优秀的文献资料。参考USING文件可以学习如何使用Memwatch可以了解Memwatch是如何初始化、如何清理以及如何进行I/O操作的等等不一而足。还有一个FAQ文件旨在帮助用户解决使用过程遇到的一般问题。最后还有一个test.c文件提供工作案例参考。
![cw memwatch output](http://images.techhive.com/images/article/2015/11/cw_memwatch_output-100627038-large.idge.png)
Memwatch
不同于MtraceMemwatch的输出产生的日志文件通常是memwatch.log是人类可阅读格式。而且Memwatch每次运行时总会拼接内存调试输出到此文件末尾而不是进行覆盖译改。如此便可在需要之时轻松查看之前的输出信息。
同样值得一提的是当你执行了启用Memwatch的程序Memwatch会在[标准输出][34]中产生一个单行输出,告知发现了错误,然后你可以在日志文件中查看输出细节。如果没有产生错误信息,就可以确保日志文件不会写入任何错误,多次运行的话能实际节省时间。
另一个我喜欢的优点是Memwatch同样在源码中提供一个方法你可以据此获取Memwatch的输出信息然后任由你进行处理参考Memwatch源码中的mwSetOutFunc()函数获取更多有关的信息)。
#### 注意事项 ####
跟Mtrace和Dmalloc一样Memwatch也需要你往你的源文件里增加代码你需要把memwatch.h这个头文件包含进你的代码。而且编译程序的时候你需要连同memwatch.c一块编译或者你可以把已经编译好的目标模块包含起来然后在命令行定义MEMWATCH和MW_STDIO变量。不用说想要在输出中定位行号-g编译器选项也少不了。
还有一些没有具备的特性。比如Memwatch不能检测出往一块已经被释放的内存写入操作或是在分配的内存块之外的读取操作。而且Memwatch也不是线程安全的。还有一点正如我在开始时指出在C++程序上运行Memwatch的结果是不能预料的。
#### 总结 ####
Memcheck可以检测很多内存相关的问题在处理C程序时是非常便捷的调试工具。因为源码小巧所以可以从中了解Memcheck如何运转有需要的话可以调试它甚至可以根据自身需求扩展升级它的功能。
### [Mtrace][35] ###
**开发者**: Roland McGrath and Ulrich Drepper
**点评版本**: 2.21
**Linux支持**:所有种类
**许可**GNU通用公共许可证
Mtrace是[GNU C库][36]中的一款内存调试工具同时支持Linux C和C++程序检测由malloc()和free()函数的不对等调用所引起的内存泄漏问题。
![cw mtrace output](http://images.techhive.com/images/article/2015/11/cw_mtrace-output-100627039-large.idge.png)
Mtrace
Mtrace实现为对mtrace()函数的调用跟踪程序中所有malloc/free调用在用户指定的文件中记录相关信息。文件以一种机器可读的格式记录数据所以有一个Perl脚本同样命名为mtrace用来把文件转换并展示为人类可读格式。
#### 更新内容 ####
[Mtrace源码][37]和[Perl文件][38]同GNU C库(2.21版本)一起释出,除了更新版权日期,其它别无改动。
#### 有何优点 ####
Mtrace最优秀的特点是非常简单易学。你只需要了解在你的源码中如何以及何处添加mtrace()及其对立的muntrace()函数还有如何使用Mtrace的Perl脚本。后者非常简单只需要运行指令mtrace <program-executable> <log-file-generated-upon-program-execution>(例子见开头截图最后一条指令)。
Mtrace另外一个优点是它的可收缩性体现在不仅可以使用它来调试完整的程序还可以使用它来检测程序中独立模块的内存泄漏。只需在每个模块里调用mtrace()和muntrace()即可。
最后一点因为Mtrace会在mtace()(在源码中添加的函数)执行时被触发,因此可以很灵活地[使用信号][39]动态地在程序执行周期内使能Mtrace。
#### 注意事项 ####
因为mtrace()和mauntrace()函数在mcheck.h文件中声明所以必须在源码中包含此头文件的调用是Mtrace运行mauntrace()函数并非[总是必要][40]的根本因此Mtrace要求程序员至少改动源码一次。
了解需要在编译程序的时候带上-g选项[GCC][41]和[G++][42]编译器均由提供),才能使调试工具在输出展示正确的行号。除此之外,有些程序(取决于源码体积有多大)可能会花很长时间进行编译。最后,带-g选项编译会增加了可执行文件的内存因为提供了额外的调试信息因此记得程序需要在测试结束不带-g选项重新进行编译。
使用Mtrace你需要掌握Linux环境变量的基本知识因为在程序执行之前需要把用户指定文件mtrace()函数用以记载全部信息的路径设置为环境变量MALLOC_TRACE的值。
Mtrace在检测内存泄漏和尝试释放未经过分配的内存方面存在局限。它不能检测其它内存相关问题如非法内存访问、使用未初始化内存。而且[有人抱怨][43]Mtrace不是[线程安全][44]的。
### 总结 ###
不言自明,我在此讨论的每款内存调试器都有其优点和局限。所以,哪一款适合你取决于你所需要的特性,虽然有时候容易安装和使用也是一个决定因素。
要想捕获软件程序中的内存泄漏Mtrace最适合不过了。它还可以节省时间。由于Linux系统已经预装了此工具对于不能联网或者不可以下载第三方调试调试工具的情况Mtrace也是极有助益的。
另一方面相比Mtrace,Dmalloc不仅能检测更多错误类型还你呢个提供更多特性比如运行时可配置、GDB集成。而且Dmalloc不像这里所说的其它工具它是线程安全的。更不用说它的详细资料了这让Dmalloc成为初学者的理想选择。
虽然Memwatch的资料比Dmalloc的更加丰富而且还能检测更多的错误种类但是你只能在C语言写就的软件程序上使用它。一个让Memwatch脱颖而出的特性是它允许在你的程序源码中处理它的输出这对于想要定制输出格式来说是非常有用的。
如果改动程序源码非你所愿那么使用Electric Fence吧。不过请记住Electric Fence只能检测两种错误类型而此二者均非内存泄漏。还有就是需要了解GDB基础以最大程序发挥这款内存调试工具的作用。
Memcheck可能是这当中综合性最好的了。相比这里所说其它工具它检测更多的错误类型提供更多的特性而且不需要你的源码做任何改动。但请注意基本功能并不难上手但是想要使用它的高级特性就必须学习相关的专业知识了。
--------------------------------------------------------------------------------
via: http://www.computerworld.com/article/3003957/linux/review-5-memory-debuggers-for-linux-coding.html
作者:[Himanshu Arora][a]
译者:[译者ID](https://github.com/soooogreen)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:http://www.computerworld.com/author/Himanshu-Arora/
[1]:https://openclipart.org/detail/132427/penguin-admin
[2]:https://en.wikipedia.org/wiki/Manual_memory_management
[3]:http://dmalloc.com/
[4]:https://www.owasp.org/index.php/Double_Free
[5]:https://stuff.mit.edu/afs/sipb/project/gnucash-test/src/dmalloc-4.8.2/dmalloc.html#Fence-Post%20Overruns
[6]:http://dmalloc.com/releases/notes/dmalloc-5.5.2.html
[7]:http://www.gnu.org/software/gdb/
[8]:http://dmalloc.com/docs/
[9]:http://dmalloc.com/docs/latest/online/dmalloc_26.html#SEC32
[10]:http://dmalloc.com/docs/latest/online/dmalloc_23.html#SEC29
[11]:https://en.wikipedia.org/wiki/Memory_management#Dynamic_memory_allocation
[12]:https://en.wikipedia.org/wiki/Segmentation_fault
[13]:https://en.wikipedia.org/wiki/GNU_Compiler_Collection
[14]:http://www.gnu.org/software/gdb/
[15]:https://launchpad.net/ubuntu/+source/electric-fence/2.2.3
[16]:http://valgrind.org/docs/manual/mc-manual.html
[17]:http://valgrind.org/info/developers.html
[18]:http://valgrind.org/
[19]:http://valgrind.org/docs/manual/dist.news.html
[20]:http://valgrind.org/docs/manual/mc-manual.html#mc-manual.suppfiles
[21]:http://valgrind.org/docs/manual/mc-manual.html#mc-manual.mempools
[22]:http://stackoverflow.com/questions/4642671/c-memory-allocators
[23]:http://valgrind.org/docs/manual/mc-manual.html#mc-manual.monitor-commands
[24]:http://valgrind.org/docs/manual/mc-manual.html#mc-manual.clientreqs
[25]:http://valgrind.org/docs/manual/valgrind_manual.pdf
[26]:http://sourceforge.net/p/valgrind/mailman/message/30292453/
[27]:https://msdn.microsoft.com/en-us/library/ee798431%28v=cs.20%29.aspx
[28]:http://www.computerworld.com/article/2484425/linux/5-free-linux-text-editors-for-programming-and-word-processing.html?nsdr=true&page=2
[29]:http://valgrind.org/docs/manual/manual-core.html#manual-core.limits
[30]:http://valgrind.org/info/
[31]:http://www.linkdata.se/sourcecode/memwatch/
[32]:http://www.cecalc.ula.ve/documentacion/tutoriales/WorkshopDebugger/007-2579-007/sgi_html/ch09.html
[33]:http://c2.com/cgi/wiki?WildPointer
[34]:https://en.wikipedia.org/wiki/Standard_streams#Standard_output_.28stdout.29
[35]:http://www.gnu.org/software/libc/manual/html_node/Tracing-malloc.html
[36]:https://www.gnu.org/software/libc/
[37]:https://sourceware.org/git/?p=glibc.git;a=history;f=malloc/mtrace.c;h=df10128b872b4adc4086cf74e5d965c1c11d35d2;hb=HEAD
[38]:https://sourceware.org/git/?p=glibc.git;a=history;f=malloc/mtrace.pl;h=0737890510e9837f26ebee2ba36c9058affb0bf1;hb=HEAD
[39]:http://webcache.googleusercontent.com/search?q=cache:s6ywlLtkSqQJ:www.gnu.org/s/libc/manual/html_node/Tips-for-the-Memory-Debugger.html+&cd=1&hl=en&ct=clnk&gl=in&client=Ubuntu
[40]:http://www.gnu.org/software/libc/manual/html_node/Using-the-Memory-Debugger.html#Using-the-Memory-Debugger
[41]:http://linux.die.net/man/1/gcc
[42]:http://linux.die.net/man/1/g++
[43]:https://sourceware.org/ml/libc-help/2014-05/msg00008.html
[44]:https://en.wikipedia.org/wiki/Thread_safety