[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]

Re: Memory leaks ???

Igmar Palsenberg writes:
>A struct passwd * pwd is allocated, and filled by the getpwnam function,
>but it is never free'd.

getpwnam does return a pointer, but it's a pointer to static memory.
Every time you call getpwnam, it writes over the same area.  Try to
free() that pointer some time in test code, and watch free() cause a
segmentation violation.  :-)

To quote from the book mentioned in my .sig (plug, plug... :-), "The
structures are static structures that are overwritten the next time
the function is called, so if you need to keep a structure around for
any reason, you need to make a copy of it."

If you are using glibc 2.1.x, there are actually some memory tracing
facilities built into glibc that you can use to track memory leaks,
as well as memory corruption.  (I don't know what of this facility
is available in earlier versions of glibc.)

Here are code snippets to use to enable full checking:

#define USE_MCHECK 1
#include <mcheck.h>

mcheck_out(enum mcheck_status reason) {
    char *explanation;

    switch (reason) {
        case MCHECK_DISABLED:
            explanation = "Consistency checking is not turned on."; break;
        case MCHECK_OK:
            explanation = "Block is fine."; break;
        case MCHECK_FREE:
            explanation = "Block freed twice."; break;
        case MCHECK_HEAD:
            explanation = "Memory before the block was clobbered."; break;
        case MCHECK_TAIL:
            explanation = "Memory after the block was clobbered."; break;
    printf("%s\n", explanation);


main(int argc, char *argv[]);

Or you can link against -lmcheck, but that doesn't give you the
abort function, I think.  And it won't give you mtrace

export MALLOC_CHECK_=1
if you linked against -mcheck

export MALLOC_TRACE=<some_file_name>
<run your program>
mtrace <some_file_name>

And you will get a report on leaks.

This is covered in more detail in the glibc info pages.


"Magazines all too frequently lead to books and should be regarded by the
 prudent as the heavy petting of literature."            -- Fran Lebowitz
 Linux Application Development     http://people.redhat.com/johnsonm/lad/

[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index] []