[英]how to free an allocated array in a function in c
如果我们使用malloc()
在main()
,我们可以free()
在动态内存分配main()
但是,如果我们在不同的函数中使用malloc()
并且在main()
使用该函数,那么我们应该在哪里调用free()
来释放在该函数中分配的内存?
即,在以下源代码中:
#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;
}
这是最好的方法吗?
当不再需要内存时,应该释放内存。
由于在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);
}
在你完成它之后 - free
动态分配的内存。 但是设计明智-您也可以在其他功能中调用free
来正确管理它。 这真的取决于。 对此没有硬性规定。
例如在这里你应该将该指针返回到分配的内存,然后在main
使用它之后你可以在main()
释放它。
所以结构将类似于
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;
}
然后在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;
}
但是是的,正确命名函数- 如果您要使用名称memory_allocate_function
函数,则仅执行此操作 - 不应存在任何其他主要逻辑。 这有助于创建良好的可读代码。
请注意一件事 - 在这里,当您调用该函数然后退出该函数时,该函数是唯一包含它的地址的局部变量,它的存储持续时间已结束,您将永远无法访问您分配的内存。 这是内存泄漏的一种情况。 如果您确定不会从函数返回指向内存的指针 - 然后使用它(在相同的函数中或不同的函数中)然后释放它(在函数的范围结束之前 - 注意不要提到你会在哪里释放它,您可以在相同的功能和其他功能中也可以这样做)。
我忍不住要提几件事情:- 1) 不要强制转换malloc
的返回值。 2) 检查malloc
的返回值 - 如果它是NULL
你想单独处理它。 3) main()
) 的推荐签名是int main(void)
如果你需要malloc
存储功能于一体,并free
在另一个,你必须以某种精心传递指针指向malloc
从点编内存malloc
到您想要的点free
它。
您有责任保留指针值并将其从一个函数传递到另一个函数,直到它到达free
点。 如果在此过程中丢失了该值,则会发生内存泄漏。 内存泄漏就是您现在所拥有的,因为您没有在任何地方传递该本地array
指针。
没有“一种真正的方法”可以做到这一点,因为这取决于您的具体意图。 例如,您可以从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.