Question

Let's say I have a malloc'd struct with certain fields:

typedef struct myStruct {
    int integer;
    char* array;
    ...
    }

I malloc an array of this structs but, when I want to free them, should I just:

/* Loop */
free(myStruct[i])
myStruct[i] = NULL

free(myStruct)

Or should I free every field of the structure, and then the struct itself?

No correct solution

OTHER TIPS

If you call malloc like this:

myStruct *s = malloc(sizeof(myStruct ));

then you should call free on whatever pointer was returned from malloc (in this case called s):

free(s);

The same thing goes if you call malloc like this:

myStruct *s = malloc(sizeof(myStruct) * NUM_IN_ARRAY); //... free(s);

Although, if you previously assigned a malloc'd pointer to a char* field in the structure, remember you need to free that as well.

If your char* array values were individually malloced, you need to loop over each element of the struct array and free them first - otherwise you end up with "unreachable" memory and thus a leak.

The only time this doesn't really matter is at termination of a program - anything you didn't clean up will be done for you.

Possible code sample:

typedef struct myStruct {
  int integer;
  char* array;
  ...
}

myStruct* A;
int N;
A = malloc(N * sizeof *A);
for(int ii=0; ii<N; ii++) A[ii].array = malloc(20);

Now if you did

free(A); A=NULL;   // ****** BAD - DON'T DO IT ******

You would end up with a memory leak. Instead you will need to loop over each element, and free the array inside the struct:

for(int ii=0; ii<N; ii++) {
  free(A[ii].array);
  A[ii].array=NULL;
}
free(A); A=NULL;

You should free what you mallocated.

So for each malloc (or strdup) you should have one and only one matching free.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top