Thread: Where do I call free() to prevent memory leakes for this C program

  1. #16
    Registered User
    Join Date
    May 2012
    Posts
    1,066
    Quote Originally Posted by redworker View Post
    I tried free(results); but that breaks the program as its returning results as well. Where do I call it then?
    As grumpy has already told you in post #5, you have to free the memory in the caller of these functions. Thus you have to climb up the call stack until you find a place where your program doesn't need the resource anymore.

    So for example you have to look at every function which calls save_string() and decide whether it's possible to free the memory there. If not you have to look again at the caller and so on.

    Bye, Andreas

  2. #17
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    Mmm, giving away too much I think
    Code:
    void freeHash(htable) 
    {      
      if (!htable) return;
      for (int i=0; i<tsize; i++) {
        h_ptr list = htable[i];
        while ( list ) {
          h_ptr temp = list;
          list = list->next;
          free( temp->word );  // the string
          free( temp );  // the node
        }
      }
      free(htable);
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #18
    Registered User
    Join Date
    May 2011
    Posts
    12
    @Salem, this code seems to be working fine and got rid of most of the errors. I also set all global variables to 0/NULL too. It cleared the pointer related leaks and I will be able to fix rest.

    Thanks for your help.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 12-28-2012, 04:07 PM
  2. Program that displays amount of free memory
    By trancedeejay in forum Linux Programming
    Replies: 3
    Last Post: 01-13-2006, 01:27 PM
  3. Making a program to free up Ram memory
    By cfrost in forum Windows Programming
    Replies: 1
    Last Post: 10-03-2004, 06:52 AM
  4. How to prevent exiting from running program
    By scorpio_IITR in forum Linux Programming
    Replies: 5
    Last Post: 01-18-2004, 04:15 AM
  5. How to free memory in this program
    By Coconut in forum C Programming
    Replies: 1
    Last Post: 10-26-2002, 10:57 PM

Tags for this Thread