Hi,
I want to know how to program to find memory leak. my idea is to find whether there is a free() for every malloc before exiting the function.

x()
{
malloc()
....

if()
{
abc
return; // thr is a memory leak as thr is no free n we are returning from the function.
}
.....
.....
free()
}

Recommended Answers

All 14 Replies

> my idea is to find whether there is a free() for every malloc before exiting the function.
Is this a memory leak?

void foo ( char *msg ) {
  char *p = malloc( 10 );
  if ( strlen(msg) >= 10 ) {
    free( p );
    p = NULL;
  } else {
    strcpy( p, msg );
  }
  return p;
}

int main ( ) {
  char *p = foo( "hello" );
  if ( p ) {
    printf( "Yay %s\n", p );
    free( p );
  }
  return 0;
}

Must be char* foo ( const char *msg ) { , of course ;)...

commented: Absolutely!!! Good catch :) +20

One way to do it is to write your own malloc() and free() functions which keep track of the allocated pointers in a linked list. Then just before program exit run through the linked list to find the pointers that have not been freed.

struct node
{
    unsigned int line_number;
    char* file;
    void* ptr;
    struct node* next;
};

void* mymalloc(unsigned int size, unsigned ine line_number, const char*filename)
{
    void* ptr = malloc(size);
     // now add the pointer to the linked list, not shown 

    return ptr;
}

void myfree(void* ptr)
{
    // search list for ptr and when (and if) found delete the node
    // code is not shown here

    free(ptr);
}

int main()
{
     // example use.  Note:  I don't know if all compilers support __LINE__ and
     // __FILE__ macros or not.  __LINE__ is a preprocessor directive that 
     // returns the current line number of the file being compiled, and
     // __FILE__ is a preprocessor directive that returns the file name
     //  of the current file being compiled.
     int* array = mymalloc( sizeof(int * 10), __LINE__, __FILE__);

}
commented: solid advice. this is the best way to handle memory allocation/deallocation +4

Thanks for the reply. But my requirement was different. This code works fine when you want to write new program. What i want is to find a missing free() in existing code. In a big application, you come across the below sub sections. Then how do you deal with it ? there needs to be a memory trailer (as a part of debugging)to check whether memory was freed before exiting.

void foo ( char *msg ) {
  char *p = malloc( 10 );
  if ( strlen(msg) >= 10 )   -> at this point if free was missed ?
      return;
  else {
    strcpy( p, msg );
  }
  return p;
}
int main ( ) {
  char *p = foo( "hello" );
  if ( p ) {
    printf( "Yay %s\n", p );
    free( p );
  }
  return 0;
}

> my idea is to find whether there is a free() for every malloc before exiting the function.
Is this a memory leak?

void foo ( char *msg ) {
  char *p = malloc( 10 );
  if ( strlen(msg) >= 10 ) {
    free( p );
    p = NULL;
  } else {
    strcpy( p, msg );
  }
  return p;
}

int main ( ) {
  char *p = foo( "hello" );
  if ( p ) {
    printf( "Yay %s\n", p );
    free( p );
  }
  return 0;
}

Which OS/Compiler are you using sreesai ?

GCC .

Is this an assignment, just to go through and count occurrences of these particular functions within some *.c file?

I ask, because for most "REAL WORLD" programs you can't just merely write a script that counts the occurrences of malloc with the occurances of free and check that they're equal.

real world programs are not always nice and neat with a free following every malloc like how you expect HTML files always to always have a "close tag" occuring somewhere inline after its corresponding "open tag".

typically memory leaks occur because the program logic often calls functions or conditionally executes blocks of codes that contain either a malloc or a free -- but not both -- and the programmer misses some unexpected condition in the logic and therefore makes (or forgets) an unaccounted call to malloc or free.

memory allocation problems is the bane of program debugging. there are far too many programmers out there who think they're somehow "cool" because they use malloc, even though 99% of the time they don't need to.

combine this with the fact that many of these characters tend to write sloppy, convoluted code, and you'll begin to understand Why I F-ing Hate Malloc

.

Well 'GCC' is only half an answer, so let me guess the other half of the answer and say the OS is 'Linux'.

In which case, try this command line valgrind myprog

Well 'GCC' is only half an answer, so let me guess the other half of the answer and say the OS is 'Linux'.

In which case, try this command line valgrind myprog

no...its unix. does your command work for unix as well ?

well...what you said is correct. i am looking at the RTOS where in some condition inside a function call is not met and you need to exit and miss the malloc'd memory that was allocated initially. so you can't check each and every function call where you called a malloc and all the exit conditions for a free. Real time code which is very large has chances of having such code. so you need to have a code which checks for such missed free() calls.

Is this an assignment, just to go through and count occurrences of these particular functions within some *.c file?

I ask, because for most "REAL WORLD" programs you can't just merely write a script that counts the occurrences of malloc with the occurances of free and check that they're equal.

real world programs are not always nice and neat with a free following every malloc like how you expect HTML files always to always have a "close tag" occuring somewhere inline after its corresponding "open tag".

typically memory leaks occur because the program logic often calls functions or conditionally executes blocks of codes that contain either a malloc or a free -- but not both -- and the programmer misses some unexpected condition in the logic and therefore makes (or forgets) an unaccounted call to malloc or free.

memory allocation problems is the bane of program debugging. there are far too many programmers out there who think they're somehow "cool" because they use malloc, even though 99% of the time they don't need to.

combine this with the fact that many of these characters tend to write sloppy, convoluted code, and you'll begin to understand Why I F-ing Hate Malloc

.

> no...its unix. does your command work for unix as well ?
If it's installed.

You could just type 'valgrind' to see whether you get "command not found" or something else.

Of course, "Unix" is just as vague as "Windows" is. There are a multitude of operating systems that could be called "Unix" in the broadest sense of the word.
Try the valgrind website for more details to see if your particular variant is supported.

some conditions inside a function call is not met and you need to exit and miss the malloc'd memory that was allocated initially.

yeah, that's a common event causing memory leaks.

so my point was that merely counting 'x' number of malloc() and 'x' number of free() commands does not indicate that your memory allocation is somehow going to be free of leaks.

if you must use memory allocation, do something similar to what AncientDragon earlier posted: replace malloc() and free() with your own functions that include a tracking mechanism such as a linked list

You can even use fancy preprocessor macros and so on to replace the malloc()/free() calls in existing code with your own functions.

BTW, __LINE__, __FILE__, __DATE__, and __TIME__ are all standard C89 as far as I know.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.