Memory leaks

From OraWiki

Jump to: navigation, search

What is a memory leak?

Memory leaks are the reason for a lot of stupids to say C/C++ language is a bad language because a programmer have to worry about pointers and memory management and "garbage collection" because C/C++ do not have any "garbage collection" and memory leaks are very often the result of misused pointers.

I love pointers! 
They are great! Believe it. 
If you understand the pointer concept and if you are able to read C language code like a book 
than you will not have any problem with them! 
I bet they help you to be really successful!

Nevertheless it can be difficult to find problems if a programmer is not able to use them correctly. 
It take some time to understand pointers! It helps to learn Assembly language but this is not a must!

A memory leak is given if a programmer made a mistake using functions which allocates memory. For example: (REMARK: You can run this code for a while but you have to kill it manual because it will run until there is no free memory and than your system is dead!)


#include <stdio.h>
#include <stdlib.h>

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


char * text;  /* A pointer to one character arrays */

    for (;;)      /* Endless loop ! */
    {
         text= ( char *) malloc( 1024);   /* Allocate 1024 bytes every 60 seconds...*/
         sleep(60);
    }
return 0;
}


Problem of the code above is that the information where memory allocated by malloc exists is lost after additional calls of malloc. The programmer does not have a chance to free allocated memory because the information of the pointer variable char *text is lost after each call of malloc.

A better way would be:


#include <stdio.h>
#include <stdlib.h>

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


char * text==NULL;  /* A pointer to one character arrays */

    for (;;)      /* Endless loop ! */
    {
         if (text == NULL )
         text= ( char *) malloc( 1024);   /* Allocate 1024 bytes every 60 seconds...*/
         sleep(60);                       /* Sleep for 60 seconds */
         if (text != NULL)                /* Malloc can fail! If it have allocated memory only than free it! */
         {
             free(text);                  /* Free memory allocated by malloc ! */
             text=NULL;                   /* Set pointer to memory to NULL     */
         }
    }
return 0;
}

The stuff above will run endless without any problem. It allocates and deallocates memory.

Remember:

after an alloc a free should follow!
malloc, realloc, calloc and so an are so called sandwich functions!
After an alloc a free should follow! 
(There are exceptions. Probably you need allocated memory during complete runtime!)

You should also remember that there are a lot of functions allocating memory implicit like

strdup
strcat


If you duplicated a string using strdup you should free this memory if it is not required anymore!

Personal tools