代码之家  ›  专栏  ›  技术社区  ›  Yuki

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

  •  -1
  • Yuki  · 技术社区  · 2 年前

    我的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

    1 回复  |  直到 2 年前
        1
  •  0
  •   dbush    2 年前

    每次呼叫 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 循环运行5次 fooStruct 的成员 struct thing 。所以你想以相反的顺序释放它。

    尝试3是最接近的。你在打电话 自由的 循环两次,但你只打了电话 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);