Dingle Box
Dingle Box

Reputation: 53

freeing memory in a while loop keeps getting stuck an infinite loop

I just wanted this while loop to go through each slot of party -> fragments and free each spot if it isn't NULL, but it seems to be getting stuck in an infinite loop instead when I go to run it. If I insert an else and put a break in it, it'll run, but I still have memory leaks.

  while(i < party -> num_active_fragments)
  {
    if(party -> fragments[i] != NULL)
    {
      free(party -> fragments[i]);
      i++;
    }
  }

Upvotes: 4

Views: 211

Answers (2)

chqrlie
chqrlie

Reputation: 144989

The reason you get an infinite loop is i is only incremented if party->fragments[i] is not NULL.

It is less error prone to use for for this type of loop and not modify the loop index inside the body of the loop:

for (i = 0; i < party->num_active_fragments; i++) {
    if (party->fragments[i] != NULL) {
        free(party->fragments[i]);
    }
}

Furthermore, you can pass null pointers to free that will ignore them and you should set the freed pointers to NULL to avoid later reference:

for (i = 0; i < party->num_active_fragments; i++) {
    free(party->fragments[i]);
    party->fragments[i] = NULL;
}

Upvotes: 2

Eduardo Pascual Aseff
Eduardo Pascual Aseff

Reputation: 1166

The problem here is that i++ should be out of the if statement. The infite loop is caused because an element is NULL and in that iteration i is not incremented, and same happens repeatedly.

As people commented, there is no need for checking if the value is NULL.

And as @thebusybee commented, you should set the freed pointers as NULL.

Your code may look like this:

while(i < party->num_active_fragments)
{
    free(party->fragments[i]);
    party->fragments[i] = NULL;    
    i++;
}

Upvotes: 4

Related Questions