gpt4 book ai didi

C 内存分配、结构数组中的段错误/双重释放

转载 作者:行者123 更新时间:2023-12-02 09:17:10 27 4
gpt4 key购买 nike

据我了解,段错误是指您尚未正确分配内存,而双重释放是指您尝试释放已经释放的内存?

增加结构体数组大小的正确方法是什么?您实际上需要释放哪些部分?

我有一个结构:

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 = . . . )可以工作,但显然是错误的,因为我没有释放任何东西,对吗?

但是当我尝试使用注释掉的代码时,我收到了双重 Free 错误

最后,(因为有一系列自动测试),显然我还需要在代码的其他部分使用 malloc 等。我还应该在哪里分配内存?

最佳答案

The line I'm using now (entries = . . . ) works, but is obviously wrong because I'm not freeing anything, right?

仅当 realloc() 失败时才是错误的。成功后,realloc()如有必要会自动释放先前分配的 block (如果是同一个 block ,并且系统可以简单地更改大小,则可能没有必要)。

所以,常见的习惯用法如下:

mytype *var = malloc(...);

// ...

mytype *tmp = realloc(var, ...);
if (!tmp)
{
free(var);
return -1; // or whatever error
}
var = tmp;

// ...

free(var);

关于C 内存分配、结构数组中的段错误/双重释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45797043/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com