【问题标题】:freeing a structure array allocated with double pointer释放用双指针分配的结构数组
【发布时间】:2016-04-01 16:18:09
【问题描述】:

这基本上是我想要做的:

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

这是我读取缓冲区的函数(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 循环放在空闲函数之前或之后,使用 top 看不到任何内存变化 在我的终端上。 这正常吗?

提前致谢,

【问题讨论】:

  • 你应该只free asStruct 一次而不是循环。

标签: c pointers memory malloc free


【解决方案1】:

调用 free 的次数必须与调用 malloc 的次数完全相同。

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

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

free(arr);

【讨论】:

  • 嗯,这行得通,但是当我冻结我的程序时,我看不到程序中的内存变化? (在我的 mac 终端中使用 top)
  • 我会再仔细检查并告诉你。任何建议(仅供参考泄漏命令不起作用)Thx :)。
  • @jonhatansmith 如果您想检查内存更改调试程序并使用 gdb x 命令检查内存,例如 x/4xw arr。查看顶部的 VIRT 列,而不是实际使用内存的 RES。如果您实际上没有写入或读取分配的内存,则操作系统实际上可能不会给您此内存,而只会说如果您尝试写入或读取该内存(并导致页面错误),您最终会得到它核心)。使用strace 跟踪您的程序进行的所有系统调用。
  • 谢谢,我会看看。现在我只能使用 lldb,但我猜它是一样的?
  • 非常感谢! Tinky_Winky!!!已经告诉过你是我在天线宝宝乐园的最爱?!!
猜你喜欢
  • 2017-08-24
  • 2021-08-07
  • 2022-01-06
  • 1970-01-01
  • 1970-01-01
  • 2021-11-26
  • 2015-10-26
  • 2020-05-06
  • 2019-11-30
相关资源
最近更新 更多