free():无效的下一个大小(快)错误

时间:2013-10-21 23:31:47

标签: c runtime-error free

我正在尝试从stdin中标记字符串。我只对字符感兴趣并构建每个字符串的数组(忽略非字符)。出于某种原因,当我从stdin读取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;
}

1 个答案:

答案 0 :(得分:3)

您继续为尺寸tempnewWord分配sizeof(200)sizeof(100),而它们都等于sizeof(int),这比您预期的要小得多

修改

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

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