0
int i = 0;

player_t** matchArray = malloc(sizeof(player_t**));
player_t *currentPlayer = playerList;

while(currentPlayer != NULL)
{
   if( strcmp(currentPlayer->nameLast, name) == 0 )
   {
     matchArray = realloc(matchArray, sizeof(matchArray) + sizeof(currentPlayer));
     matchArray[i] = currentPlayer;
     i++;
   }

   currentPlayer = currentPlayer->nextPlayer;
}

/*
   Make the matchArray NULL terminated, as we do not count the number 
   of indexes.
*/
matchArray[i] = realloc(matchArray, sizeof(matchArray) + sizeof(player_t));
matchArray[i] = NULL;

The code above dies in the while loop, when reallococating the matchArray, but only does so "sometimes". It searches through a list of pointers to structures to find the structures that have the same last name as is specified by the 'name' variable. Some names work fine, most likely because there are only a few matches. Others get the error mentioned.

What would cause this to happen?

user2893045
  • 59
  • 1
  • 6

1 Answers1

1

matchArray and currentPlayer are pointers. Sizes don't change.

You need to do

 player_t** nmatchArray = realloc(matchArray, sizeof(matchArray) * i);
 if (nmatchArray == NULL) { // error handling code }
 matchArray = nmatchArray;

Its probably better to allocate a certain number upfront instead of re-allocating each time.

rohit89
  • 5,745
  • 2
  • 25
  • 42