我试图从stdin中标记字符串。我只对字符感兴趣,并为每个字符串构建一个数组(忽略非字符)。出于某种原因,当我从stdin中读取24个或更多字符时,收到错误:
free():下一个大小(fast)无效:
这是相关的代码…它在较小的字符串(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;
}

最佳答案

您继续为大小tempnewWord分配sizeof(200)sizeof(100),而这两者都等于sizeof(int),这比您预期的要小得多。
修改

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

进入之内
temp = malloc(200);
newWord = malloc(100);

关于c - free():无效的下一个尺寸(快速)错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19506592/

10-11 23:11
查看更多