Jeegar Patel
Jeegar Patel

Reputation: 27210

how to check memory leakage in c code?

see i m using multiple time malloc & free.

so at the end of application i want to make sure there is no memory leakage. all malloc are freed.

Is there any method or function to see that?

another question : all all os mostly reclaim memory only when that application gets exit but if application is suppose to be run long time & if this way it continuously leack memory then at some time there will be no unalloacated memory & application will be crash or system will re-boot...!! Is it true..???

Upvotes: 0

Views: 401

Answers (4)

Nalin Kanwar
Nalin Kanwar

Reputation: 120

First, You should compile your code with debugging support (In gcc, it is -g). Note that this isn't a necessity but this enables the debugger to provide you with line numbers as one of the advantages.

Then you should run your code with a nice debugger like valgrind or gdb or whatever. They should tell you the lines where the memory was allocated but not freed.

Valgrind is a very powerful tool for debugging. You'd need to use the --tool=memcheck option (which i think is enabled by default but doesn't hurt to know).

Upvotes: 1

n. m. could be an AI
n. m. could be an AI

Reputation: 119857

It is not guaranteed that the OS will reclaim your memory. A desktop or a server OS usually will; an embedded OS might not.

There are several debugging malloc libraries out there; google for debug malloc and use one that suits you. GNU libc has a debugging malloc built in.

Upvotes: 2

cnicutar
cnicutar

Reputation: 182619

At the end of a process the OS reclaims used memory (so it cannot "leak").

so at the end of application i want to make sure there is no memory leakage

EDIT

James raised an interesting point in the comments: "Any decent programmer should not rely on the OS to do his job". I must underline I was thinking of the following scenario:

/* mallocs */

/* frees <- useless */
exit(0);

Upvotes: 3

Jakub M.
Jakub M.

Reputation: 33827

You could wrap malloc() and free(), and count some basic statistics by yourself

#define malloc(x) malloc_stat(x)
#define free(x) free_stat(x)

static counter = 0;

void* malloc_stat( size_t s ) {
    counter++;
    return malloc(s);
}

void free_stat( p ) {
    counter--;
    free(p);
}

Upvotes: 0

Related Questions