realloc的glibc错误:下一个大小无效

时间:2013-12-09 20:41:16

标签: c glibc realloc

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;

上面的代码在while循环中死掉,当重新传播matchArray时,但只是“有时”这样做。它搜索结构指针列表,以查找具有与'name'变量指定的相同姓氏的结构。有些名字很好用,很可能是因为只有几个比赛。其他人得到了提到的错误。

会导致这种情况发生的原因是什么?

1 个答案:

答案 0 :(得分:1)

matchArraycurrentPlayer是指针。尺寸不会改变。

你需要做

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

最好先预先分配一定数量,而不是每次重新分配。