【发布时间】:2018-04-29 14:00:35
【问题描述】:
我正在尝试读取要排序的单词列表,我从一个相当小的数组(10 个元素)开始,如果当前容量不是,我想将数组的大小增加 10足够。这似乎适用于第一个 realloc,但在尝试再次调用 realloc 时我得到一个 SIGABRT。我确定这是一件我没有看到的简单事情,但我似乎无法弄清楚。这是我的程序:
int main(int argc, char *argv[]){
char *string = malloc(100);
// Array of pointers starting with 100 elements
char **toSort = malloc(100*sizeof(char *));
if(toSort == NULL) {
exit(1);
}
for(int i = 0; i < 100; i++) {
// Each string can be up to 100 characters long
toSort[i] = malloc(101);
if(toSort[i] == NULL) {
exit(1);
}
}
// Get all lines in the file
int counter = 0;
int max = 10;
char *toAdd;
FILE *txt = fopen("wlist0.txt", "r");
while(fgets ( string, 100, txt ) && counter < max) {;
toAdd = malloc(100);
if(toAdd == NULL) {
exit(1);
}
strcpy(toAdd, string);
toSort[counter] = string;
counter++;
//if the array needs to be enlarged
if(counter == max) {
char **new = realloc(toSort, (max+10) * sizeof(char));
if(new == NULL) {
exit(1);
}
for(int i = max; i < max + 10; i++) {
toSort[i] = malloc(101);
if(toSort[i] == NULL) {
exit(1);
}
}
toSort = new;
max += 10;
}
};
for(int i = 0; i < max; i++) {
char *word = toSort[i];
printf("%s", word);
}
for(int i = 0; i < max; i++) {
free(toSort[i]);
}
free(toSort);
return 0;
};
就像我的 cmets 所说,我的字符串的最大长度为 100 个字符。我想我也可以为字符串动态分配内存,但是当我让另一个 realloc 工作时我会担心这一点。任何帮助将不胜感激。
【问题讨论】:
-
你应该使用函数而不是把所有东西都放在你的
main()中。这将使您的代码更易于阅读! -
@purec 注意。我删除了它们。
-
@user3121023 谢谢!这似乎有帮助。我认为这是一件小事。
-
你说的完全正确!我已经在这方面工作了很长时间,现在我忘记整理了。
-
@purec:C 标准要求将
NULL传递给free()是有效的。