0

I have an algorithm in c in which memory is allocated using malloc many times. I wanted to write a function that would free that memory when the program is all finished but I am unsure how to structure it. Would it just be multiple calls to free()? I am rather new to C and memory allocation so any help would be greatly appreciated.

Program:

typedef struct State State;
typedef struct Suffix Suffix;

struct State {  /* prefix + suffix list */
    char*   pref[NPREF];    /* prefix words */
    Suffix* suf;            /* list of suffixes */
    State*  next;           /* next in hash table */
};

struct Suffix { /* list of suffixes */
    char *  word;           /* suffix */
    Suffix* next;           /* next in list of suffixes */
};
John
  • 139
  • 1
  • 12

1 Answers1

2

Every call to malloc should have a corresponding call to free, using the value of the pointer that was returned by malloc.

You'll need to store the values returned by malloc in your program using some sort of container, such as an array, a linked list, and call free on those values before returning from main.

Write a function along the lines of:

void freeMemory()
{
   int i = 0;
   State* sp = NULL;
   State* tmp = NULL;

   for ( i = 0; i < NHASH; ++i )
   {
      sp = statetab[i];
      while ( sp != NULL )
      {
         tmp = sp->next;
         free(sp);
         sp = tmp;
      }
   }
}

and call it from main before the return statement.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • 4
    "Every call to malloc _must_ have a corresponding free". I would say that every `malloc` _should_ have a corresponding `free`. Libraries such as GTK [don't always bother with `free`ing memory](http://stackoverflow.com/questions/16659781/memory-leaks-in-gtk-hello-world-program) – Levi May 11 '15 at 05:46
  • @John, you'll need to traverse the list and call `free` on each pointer. – R Sahu May 11 '15 at 05:50