c - 可以在 C 中返回和释放动态分配的数组吗?

标签 c function malloc dynamic-arrays

是否可以同时返回和释放动态分配的数组?

int *mycopy(int *from, int len)
{
    int i;
    int *to;

    to = malloc(len*sizeof(int));

    for(i = 0; i < len; ++i) {
        to[i] = from[i]
    }

    return to;

    // how do I free the "to" array?
    // do i even need to, or does the array only have function scope
    // and get deleted when the function exits?
}

或者是

void mycopy(int *from, int *to, int len);

我唯一的选择?

mycopy 函数只是一个简单的示例,但在实际代码中我想嵌套它们,例如调用它

a = mycopy(mycopy(b, 5), 5)

如何在每次调用函数时不分配更多内存的情况下执行此操作?谢谢。

最佳答案

如果您返回数组,调用代码必须负责释放它(函数必须释放它)。如果您不返回数组,函数必须 释放它,但无论如何该函数都毫无意义。因此,该函数不会释放数组。

如果您使用:

void mycopy(int *from, int *to, int len);

调用代码必须进行内存分配。如果您使用:

void mycopy(int *from, int **to, int len);

函数可以进行分配——但它仍然不能释放它。

但初始功能更好:写的很好。你可以这样调用它:

int b[] = { 1, 2, 3, 9, 2 };
int *a = mycopy(b, sizeof(b)/sizeof(b[0]));
...use a...
free(a);

顺便说一句,您无法承受对复制函数的嵌套调用——或者,至少,您无法使用这种方式来实现它:

a = mycopy(mycopy(b, 5), 5);

它会严重泄漏内存。如果您必须进行嵌套调用(为什么?),那么您需要:

int *c;
int *a = mycopy((c = mycopy(b, 5)), 5);

但是这样写会更干净整洁:

int *a = mycopy(b, 5);
int *c = mycopy(b, 5);

这不太容易出错,更容易理解,并且使用更少的字符来启动!

关于c - 可以在 C 中返回和释放动态分配的数组吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28945283/

相关文章:

PHP - 从另一个文件调用函数而不包含它

c++ - 检测错误源 "glibc detected memory corruption"

c++ - 以编程方式提取 .deb 包

c - log4c - 我怎样才能只看到信息消息?

c++ - 具有显式类型名称的函数模板

javascript - 合并两个 JavaScript 脚本

C 读取函数读取比请求更多的字节

c - 段错误(核心转储)错误 C linux 套接字

c - 如何正确释放 malloc 的结构?

c - C 程序中的奇怪行为,分配内存后变量损坏