C - 如何释放一个双空指针,该指针具有使用 malloc 分配给它的动态结构数组

问题描述 投票:0回答:1

我的C看起来像这样。

typedef struct thing
{
    void *fooStruct;
} thing;

typedef struct foo
{
    int *somethingNumber;
    char something;
} foo;

extern void **double_ptr;
void *ptr;

int main() {
    ptr = (struct thing*)malloc(sizeof(thing) * 5);
    double_ptr = &ptr;

    for (int i = 0; i<5 ; i++) {
        ((struct thing *)*double_ptr)[i].fooStruct = (struct foo*)malloc(sizeof(foo));
    }

    // <Things I've tried to free the memory>

    return 0;
}

我尝试了一些方法,这样我就可以释放在整个程序中分配的所有内存(所有动态“foo”结构、所有动态“thing”结构、“ptr”和“double_ptr”) '),但我总是遇到错误。尝试在这里搜索,但我没有找到任何对我有帮助的东西。

到目前为止我记得的一些尝试:

// Attempt 1:
free(double_ptr);

// Attempt 2:
for (int i = 0; i < 5; i++) { 
    aux_ptr = &((struct thing*)*double_ptr)[i]; 
    free(aux_ptr);
}

free(double_ptr);

// Attempt 3:
void *aux_ptr;

for (int i = 0; i < 5; i++) { 
    aux_ptr = ((struct thing*)*double_ptr)[i].fooStruct; 
    free(aux_ptr);
    aux_ptr = &((struct thing*)*double_ptr)[i]; 
    free(aux_ptr);
}

free(*double_ptr);

// Attempt 4:
void *aux_ptr;

for (int i = 0; i < 5; i++) { 
    aux_ptr = ((struct thing*)*double_ptr)[i].fooStruct; 
    free(aux_ptr);
    aux_ptr = &((struct thing*)*double_ptr)[i]; 
    free(aux_ptr);
}

free(double_ptr);

我希望不会出现内存泄漏(或者代码根本无法编译和运行),但这些不同的尝试并没有完全发挥作用。尝试 1 和 4 甚至无法编译(无效指针),而尝试 2 和 3 则存在内存泄漏。

指针对我来说一直是一个问题,所以如果解决方案比我想象的更容易,我很抱歉。我真的很感激一些帮助 :c

c pointers struct memory-leaks
1个回答
0
投票

对于每个对

malloc
的调用,都应该有对
free
的相应调用。

查看分配代码:

ptr = (struct thing*)malloc(sizeof(thing) * 5);
double_ptr = &ptr;

for (int i = 0; i<5 ; i++) {
    ((struct thing *)*double_ptr)[i].fooStruct = (struct foo*)malloc(sizeof(foo));
}

对于存储在

malloc
中的数组,您有一个
ptr
,然后循环中的单个
malloc
fooStruct
struct thing
成员运行 5 次。所以你想以相反的顺序释放它。

尝试 3 是最接近的。您在循环中调用了

free
两次,但在初始循环中只调用了
malloc
一次。具体来说,
&((struct thing*)*double_ptr)[i]
并不指向已分配的内存,因此请摆脱它。

void *aux_ptr;

for (int i = 0; i < 5; i++) { 
    aux_ptr = ((struct thing*)*double_ptr)[i].fooStruct; 
    free(aux_ptr);
}

free(*double_ptr);
© www.soinside.com 2019 - 2024. All rights reserved.