c - 如果指针重定向,则释放内存

标签 c pointers memory free

我无法理解如何在以下代码片段中正确释放我的内存:

char *func(char* s){

   /* do something with s */


   // pass s to function, create new string, return this string
   s = function_allocating_mem(s);

   // pass s to function, create new string, return this string
   s = other_function_allocation_mem(s);
   /* do other stuff again */

   return s;
}

int main(void){
    char str[] = "somestring";
    str = func(str);
}

现在我分配了两次不同大小的内存。但是如果我做对了,我只是改变了指针地址并且永远不会释放内存。

我真的不知道,要谷歌什么才能找到一个例子

这是否正确,我该如何更改?

编辑: 我删除了函数的第二个参数。这没有必要,而且令人困惑。

最佳答案

当你在程序中从堆中分配内存时,你必须清楚地了解:

  1. 堆内存在您的程序中的分配位置。

  2. 堆分配内存的所有权如何从一个函数转移到下一个函数,以及

  3. 在程序结束前释放它的位置。

在您的情况下,假设 function_allocating_memother_function_allocation_mem 不在输入参数上调用 free,您必须确保内存在这些函数中分配的在 funmain 中释放。

char *func(char* s, const char* os){
   char* s1 = NULL;
   char* s2 = NULL;
   /* do something with s and os */


   // pass s to function, create new string, return this string
   s1 = function_allocating_mem(s);

   // pass s to function, create new string, return this string
   s2 = other_function_allocation_mem(s1);

   /* do other stuff again */

   // Deallocate memory that was allocated by function_allocating_mem().
   free(s1);


   // Memmory allocated by other_function_allocation_mem is returned to the 
   // calling function.
   return s2;
}

int main(void){
    char str[] = "somestring";

    // This is not legal anyway.
    // str = func(str, "some other string");

    char* s = fun(str);

    // Use s ...

    // Before returning from this function, deallocate memory
    // that was allocated in the call to fun().
    free(s);
}

关于c - 如果指针重定向,则释放内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27628011/

相关文章:

c - 具有循环缓冲区的同步生产者和消费者

剪掉一段字符串

内存映射 I/O 与端口映射 I/O

c - 如何处理解码 Base64 字符串时出现的错误

c - Linux套接字程序中的recvfrom api

c - 抽象流 C

c - 使用返回指针的函数声明为指针是否会导致两个指针链?

c - 如何在没有类型定义的情况下在一行中声明多个函数指针?

c - 读取位置位置 0x1D5C4C2F 访问冲突

python - 如何使用所有可用内存