【发布时间】:2018-01-29 12:35:27
【问题描述】:
据我了解,分段错误是您尚未正确分配内存时,而 Double free 是您尝试释放已释放的内存时?
增加结构数组大小的正确方法是什么,以及您实际需要在哪里/哪些部分释放?
我有一个结构:
struct Data {
// Some variables
}
我正在初始化这些结构的数组:
int curEntries = 100;
int counter = 0;
struct Data *entries = (struct Data *)malloc(curEntries * sizeof(struct Data));
当我从 bin 文件中读取数据到这个数组中并填充每个结构时,程序会一直运行,直到需要超过 100 个结构。当时,我有以下代码来重新分配数组:
if (counter == curEntries - 1) { // counter = current index, curEntries = size of the array
entries = (struct Data *)realloc(entries, curEntries * 2 * sizeof(struct Data));
// struct Data *temp = (struct Data *)realloc(entries, curEntries * 2 * sizeof(struct Data));
// free(entries);
// entries = temp;
// free(temp);
}
我现在使用的行 (entries = . . .) 有效,但显然是错误的,因为我没有释放任何东西,对吧?
但是当我尝试使用注释掉的代码时,我得到了一个双重免费错误
最后,(因为有一系列自动测试),显然我需要在我的代码的其他部分使用 malloc 等。我还应该/我需要在哪里分配内存?
【问题讨论】:
-
Documentation for
realloc()is here and here and here and here ... 叹息 -
分段错误仅表示“某种与内存相关的错误”,并且可能由任何原因引起。 Definitive List of Common Reasons for Segmentation Faults。 “双倍免费”并不是一个正式的术语,信息在这里:What does “double free” mean?。
-
顺便说一句
curEntries * 2-->(curEntries *= 2)
标签: c arrays free dynamic-memory-allocation realloc