简体   繁体   English

如何在c中的函数中释放分配的数组

[英]how to free an allocated array in a function in c

If we were to use malloc() in main() , we could free() that dynamic memory allocation in main() .如果我们使用malloc()main() ,我们可以free()在动态内存分配main()

However, if we use malloc() in a different function and we use that function in main() , where should we call free() to release the memory allocated in that function?但是,如果我们在不同的函数中使用malloc()并且在main()使用该函数,那么我们应该在哪里调用free()来释放在该函数中分配的内存?

Ie, in the following source code:即,在以下源代码中:

#include <stdio.h>
#include <stdlib.h>

int * memory_allocate_function(int);

int main(void) {
    int n=5; //length of array, 5 for example.
    int *my_array;
    my_array = memory_allocate_function(n);
    return 0;
}

int * memory_allocate_function(int n) {
    int i;
    int *array;
    array=(int *)malloc(n * sizeof(int));
    if(array == NULL) {
        printf("can not allocate memory.");
        return NULL;
    }
    // I think i can't use "free(array);" in here.
    // Because I need that array in main().
    return array;
}

Is this the best way to do this?这是最好的方法吗?

Memory should be freed when it's no longer needed.当不再需要内存时,应该释放内存。

Since the array would no longer be accessible after memory_allocate_function exits (since the array isn't returned or otherwise made accessible to the outside), it should be freed before memory_allocate_function exits.由于在memory_allocate_function退出后数组将不再可访问(因为array未返回或以其他方式可供外部访问),因此应在memory_allocate_function退出之前释放它。

void memory_allocate_function(int n){
    int i;
    int *array;
    array = malloc(n*sizeof(int));
    if (array == NULL) {
        fprintf(stderr, "Out of memory.");
        exit(1);
    }

    // ... use the array ...

    free(array);
}

Well after you are done working with it - free the dynamically allocated memory.在你完成它之后 - free动态分配的内存。 But design wise - you can call the free in other function also to manage it properly .但是设计明智-您也可以在其他功能中调用free来正确管理它 It really depends.这真的取决于。 There is no hard rule for that.对此没有硬性规定。

For example here you should return that pointer to allocated memory and then after using it in main you can free it in main() .例如在这里你应该将该指针返回到分配的内存,然后在main使用它之后你可以在main()释放它。

So the structure would be something like所以结构将类似于

int* memory_allocate_function(int n)
{
    int i;
    int *array;
    array = malloc(n*sizeof(int));
    if(array == NULL)
    {
        printf("can not allocate memory.");
        exit(0);
    }
     return array;
}

Then in main()然后在main()

int main(void)
{
    int n=5;    //length of array, 5 for example.
    int *arr = memory_allocate_function(n);
    // work with arr
    free(arr);
    return 0;
}

But yes name the function properly - if you are going to use the name memory_allocate_function function then do that only - not any other major logic should be there.但是是的,正确命名函数- 如果您要使用名称memory_allocate_function函数,则仅执行此操作 - 不应存在任何其他主要逻辑。 This helps create a good readable code.这有助于创建良好的可读代码。


Note one thing - here when you called the function and then you exited the function the only local variable that contains address of it, it's storage duration ended and you can never then access the memory you allocated.请注意一件事 - 在这里,当您调用该函数然后退出该函数时,该函数是唯一包含它的地址的局部变量,它的存储持续时间已结束,您将永远无法访问您分配的内存。 This is a case of memory leak.这是内存泄漏的一种情况。 If you are determined that you won't return the pointer to memory from the function - then work with it (in the same function or different) and then free it (Before the scope of the function ends - notice not mentioning about where you would free it, you can do it in the same function and other function also).如果您确定不会从函数返回指向内存的指针 - 然后使用它(在相同的函数中或不同的函数中)然后释放它(在函数的范围结束之前 - 注意不要提到你会在哪里释放它,您可以在相同的功能和其他功能中也可以这样做)。

I can't help mentioning few things:- 1) Dont cast the return value of malloc .我忍不住要提几件事情:- 1) 不要强制转换malloc的返回值。 2) Check the return value of malloc - in case it is NULL you would like to handle it separately. 2) 检查malloc的返回值 - 如果它是NULL你想单独处理它。 3) The recommended signature of main() is int main(void) 3) main() ) 的推荐签名是int main(void)

If you need to malloc memory in one function and free in another, you have to somehow carefully pass the pointer to that malloc ed memory from the point of malloc to the point where you want to free it.如果你需要malloc存储功能于一体,并free在另一个,你必须以某种精心传递指针指向malloc从点编内存malloc到您想要的点free它。

This is your responsibility to preserve the pointer value and hand it from one function to another until it reaches the point of free .您有责任保留指针值并将其从一个函数传递到另一个函数,直到它到达free点。 If you lose that value along the way, you'll have a memory leak.如果在此过程中丢失了该值,则会发生内存泄漏。 A memory leak is what you have now, since you are not passing that local array pointer anywhere.内存泄漏就是您现在所拥有的,因为您没有在任何地方传递该本地array指针。

There's no "one true way" to do it, since it depends on your specific intent.没有“一种真正的方法”可以做到这一点,因为这取决于您的具体意图。 For example, you can return that pointer from memory_allocate_function , receive it main and eventually free it there例如,您可以从memory_allocate_function返回该指针,接收它main并最终在那里free

int *memory_allocate_function(int);

int main()
{
  int n = 5;
  int *arr = memory_allocate_function(n);
  ...
  free(arr);
  return 0;
}

int *memory_allocate_function(int n)
{
  int *array = malloc(n * sizeof *array);
  ...
  return array;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM