0

我正在尝试从标准输入标记字符串。我只对字符感兴趣并构建每个字符串的数组(忽略非字符)。出于某种原因,当我从标准输入读取 24 个或更多字符时,我收到错误:

free():下一个尺寸无效(快速):

这是相关代码...它适用于较小的字符串(23 个字符或更少)

char  **tokenize(int *nbr_words) {


char **list = calloc(INITIAL_SIZE, sizeof(char *));
char * temp = NULL;
temp = malloc(sizeof(200));

while(fgets(temp,200,stdin)){

char * newWord = NULL;
newWord = malloc(sizeof(100)); 
int i = 0;


while(temp[i] != '\n'){

    if(isalpha(temp[i]) && temp[i+1] != '\n'){

        strncat(newWord,&temp[i],1);
        i++;
    }

        else if(isalpha(temp[i]) && temp [i+1] == '\n'){
            strncat(newWord,&temp[i],1);
            list[*nbr_words] = newWord;
            *nbr_words += 1;
            printf("%s\n",list[*nbr_words -1]);
            i++;
            if(*nbr_words % 10 == 9){
                list = realloc(list, *nbr_words + 10);
            }
            free(newWord);
            newWord = malloc(sizeof(100));
            *newWord = NULL;



    }else{  
        if(*newWord == NULL){
            i++;
        }
        else if(*nbr_words % 10 != 9){
            list[*nbr_words] = newWord;
            *nbr_words += 1;
            printf("%s\n",list[*nbr_words-1]);
            i++;
            free(newWord);
            newWord = malloc(sizeof(100));
            *newWord = NULL;
        }else{

            list = realloc(list, *nbr_words + 10);
            list[*nbr_words] = newWord;
            *nbr_words += 1;
            printf("%s\n",list[*nbr_words-1]);
            i++;
            free(newWord);
            newWord = malloc(sizeof(100));
            *newWord = NULL;
        }
    }
}
free(temp);

temp = malloc(sizeof(200));
*temp = NULL;  
}

return list;
}
4

1 回答 1

3

您继续分配tempandnewWord为 size sizeof(200)or sizeof(100),而它们都等于sizeof(int)哪个比您预期的要小得多。

调整

temp = malloc(sizeof(200));
newWord = malloc(sizeof(100));

进入

temp = malloc(200);
newWord = malloc(100);
于 2013-10-21T23:34:09.523 回答