2013-12-09 35 views
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; 

上面的代码在while循环中死亡时,重新遍历matchArray,但只是“有时”这样做。它通过指向结构的指针列表来查找具有与'name'变量指定的姓氏相同的结构。有些名字很好,很可能是因为只有几场比赛。其他人会得到上述错误。Glibc error with realloc:无效的下一个尺寸

什么会导致这种情况发生?

回答

1

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

你需要做的

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

它可能更好地分配了一定数量的前期,而不是重新分配各一次。

相关问题