释放分配有双指针

时间:2015-12-27 17:31:21

标签: 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循环,我无法使用顶部看到任何内存更改 在我的终端上。 这是正常的吗?

提前致谢,

1 个答案:

答案 0 :(得分:2)

对于malloc的调用,您必须具有完全相同的调用次数。

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

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

free(arr);
相关问题