c - 释放使用双指针分配的结构数组

标签 c pointers memory malloc free

这基本上是我想要做的:

释放使用双指针在不同范围内分配的内存。 以下代码不完整,但完整描述了我要执行的操作。

所以这是我读取缓冲区的函数(C 伪代码)

 char *read_buffer(char *buf, myStruct **arr, int nbElm)
 {
     buf = malloc(...);
     ...//many things done (use of the read(),close()... functions
     ...//but not referencing any of the buffer to my structure
     ...
     *arr = (myStruct *) = malloc(sizeof(myStruct) * nbElm);
     return (buf);
 }

这是我在内存分配和释放尝试之间使用的函数类型:

 void using_struct(myStruct *ar, int nbElm)
 {
     int i;

     i = 0;
     while (i < nbElm)
     {
         // Here I use my struct with no problems
         // I can even retrieve its datas in the main scope
         // not memory is allocated to it.
     }
 }

我的主要功能:

int main(void)
{
    char *buf;
    myStruct *arStruct;
    int nbElm = 4;

    buf = read_buffer(buf, &arStruct, nbElm);
    using_struct(arStruct, nbElm);
    free(buf);
    buf = NULL;
    free(arStruct);
    while(1)
    {;}
    return (1);
}

唯一的问题是我将 while 循环放在 free 函数之前或之后,使用 top 看不到任何内存变化 在我的终端上。 这正常吗?

提前致谢

最佳答案

您对 free 的调用次数必须始终与对 malloc 的调用次数完全相同。

myStruct **arr;
*arr = malloc(sizeof(myStruct) * nbElm);

这意味着您需要单次调用以释放第一个 nbElm 结构:

free(arr);

关于c - 释放使用双指针分配的结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34482957/

相关文章:

c++ - 使用指针替换cpp中字符串中的字符

使用 malloc 的连续内存块

c - 结构和整数的内存顺序

php - 如何在 PHP 中查找对象使用的内存? (大小)

iPhone 开发 - iPhone 应用程序的内存限制

无法从另一个进程打开信号量

c - 如何用c语言编写一个简单的malloc函数

枚举可以被认为是不安全的吗?

c++ - mysqlclient库联动问题

c++ - 删除指针失败