释放需要返回的动态分配的int,但不能在main中释放

Gra*_*man 1 c free memory-leaks

正如我的长标题所说:我试图在c中返回一个动态分配的指针,我知道,我必须释放它,但我不知道如何对待自己,我的搜索显示它只能被释放main,但我不能让用户释放int.

我的代码现在看起来像这样,

int *toInt(BigInt *p)
{
    int *integer = NULL;

    integer = calloc(1, sizeof(int));

    // do some stuff here to make integer become an int from a passed
    // struct array of integers

    return integer;
}
Run Code Online (Sandbox Code Playgroud)

我试过制作一个临时变量并看到整数然后释放整数并返回临时值,但这没有用.必须有一种方法可以做到这一点,而不是在主?

Lun*_*din 5

程序设计方面,你应该总是让执行分配的"模块"(翻译单元)负责释放内存.期待一些其他模块或调用者来释放()内存确实是糟糕的设计.

不幸的是,C没有构造函数/析构函数(也不是"RAII"),因此必须使用单独的函数调用来处理.从概念上讲,你应该像这样设计程序:

#include "my_type.h"

int main()
{
  my_type* mt = my_type_alloc();
  ...
  my_type_free(mt);
}
Run Code Online (Sandbox Code Playgroud)

至于您的具体情况,不需要动态分配.只需将分配留给调用者,并使用专用的错误类型来报告错误:

err_t toInt (const BigInt* p, int* integer)
{
   if(bad_things())
     return ERROR;

   *integer = p->stuff();

   return OK;
}
Run Code Online (Sandbox Code Playgroud)

哪些err_t是自定义错误处理类型(可能是枚举).