c - 第二次调用后Realloc失败
问题描述
我正在尝试读取要排序的单词列表,我从一个相当小的数组(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;
};
就像我的评论说的那样,我的字符串的最大长度为 100 个字符。我想我也可以为字符串动态分配内存,但是当我让另一个 realloc 工作时我会担心这一点。任何帮助将不胜感激。
解决方案
此代码将值分配给toSort
它指向的内存被释放/修改后realloc()
:
//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); <--- toSort is invalid here
if(toSort[i] == NULL) {
exit(1);
}
}
toSort = new;
max += 10;
}
这将更好地工作:
//if the array needs to be enlarged
if(counter == max) {
char **new = realloc(toSort, (max+10) * sizeof( *new )); <-- fixed here, too
if(new == NULL) {
exit(1);
}
toSort = new;
for(int i = max; i < max + 10; i++) {
toSort[i] = malloc(101);
if(toSort[i] == NULL) {
exit(1);
}
}
max += 10;
}
您的代码中可能还有其他错误。我还没有完全检查它。
推荐阅读
- nginx - Nginx 提供“位置 /”但不提供 /etc/nginx/sites-available/ 配置文件中指定的“位置 /project-name/”
- elasticsearch - 向 Security Onion 中的 elk 堆栈发送 snort 警报
- keras - 无法将使用 Keras 训练的 Resnet 模型转换为 CoreML 模型
- video - 以 10 fps 生成合成测试视频计数,第一帧被复制
- unity3d - 序列化属性不会在自定义编辑器中更改
- seo - AMP 故事在 Google AMP 验证中被标记为 noindex,但 AMP 故事中没有 noindex 标签
- sql - 包含 CLR 的 CTE 的 Sql 服务器查询在加入超过 5 个表后返回空字符串
- xml-parsing - TYPO3 从文件中流体解码 XML
- angular - 在调用 AppComponent.ngOnInit 之前加载数据
- postgresql - postgresql全文搜索,把自然数“01”当作“1”