问题
1) Is there also any memory leak tool called Boehmgc
? How is that tool compared to others?
2) I have used LeakTracer
, mudflap
and Valgrind
. But unfortunately LeakTracer has the disadvantage of memory hogging (pooling a lot of memory at start and then allocating it), so what are the alternatives?
回答1:
Boehm GC is a garbage collector, similar to the garbage collection in Java. The other tools you mention are designed to warn you about leaks, such that you can take corrective action. Garbage collection is designed to find and recover no-longer used allocations, as the program runs. Example (from wikipedia page):
#include <assert.h>
#include <stdio.h>
#include <gc.h>
int main(void)
{
int i;
GC_INIT();
for (i = 0; i < 10000000; ++i)
{
// GC_MALLOC instead of malloc
int **p = GC_MALLOC(sizeof(int *));
int *q = GC_MALLOC_ATOMIC(sizeof(int));
assert(*p == 0);
// GC_REALLOC instead of realloc
*p = GC_REALLOC(q, 2 * sizeof(int));
if (i % 100000 == 0)
printf("Heap size = %zu\n", GC_get_heap_size());
}
// No free()
return 0;
}
Personally there's something about using garbage collection in C or C++ that makes me quite uneasy. For C++ "Smart pointers" are the way to go in my opinion in scenarios where ownership is unclear (although you might want to have a thing about why it's unclear in your design) and for help with exception safety (E.g. what the now deprecated std::auto_ptr was designed for)
As for the leak detectors you can add:
- ccmalloc
- dmalloc
- NJAMD (Not just another memory debugger)
- mpatrol
- YAMD (yet another malloc debugger)
To your list of Linux ones.
Related memory checking tools, but not leaks:
- Electric fence
来源:https://stackoverflow.com/questions/7229077/problem-with-memory-leak-check-tools-in-linux