gpt4 book ai didi

c - 如果您不释放函数中动态分配的内存,会发生什么情况?

转载 作者:太空宇宙 更新时间:2023-11-04 06:27:32 26 4
gpt4 key购买 nike

我正在学习如何用 C 编写函数来接受数组并返回修改后的数组。

在函数 testfunc 中(应该简单地将 10 添加到输入数组 b 的每个元素)我正在为 npts 使用 malloc 的整数个数。但是因为我想使用指针返回这个数组,所以我没有在函数结束时释放这个内存。假设我像在代码中那样调用此函数 100 次,那么在代码期间分配的所有内存会发生什么情况?代码使用的内存量是100*10*4字节吗?对于一个不适用于动态内存分配的函数,我认为当函数返回最终值时分配给变量的内存会消失,当它再次被调用时,它会再次分配内存等等。但我对这种情况下发生的事情感到困惑。

我无法释放函数内分配的内存,因为我需要它将数组返回给主函数,而且我需要为不同的数组调用此函数超过 100 次,所以如果它一次又一次地继续分配,它会耗尽内存

有没有办法检查代码使用了多少内存? (除了查看 Mac-OSX 上的事件监视器)。

谢谢!

/* code to test returning array from functions */

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

int* testfunc(int *a,int npts);

int main(int argc, char* argv[])
{
int *b;
int a[10],i,j,npts=10;

b=(int *) malloc(sizeof(int)*npts);

for (j=0; j <100; j++)
{
printf("iteration number %d \n",j);
for (i=0; i<npts; i++)
{
a[i]=i;
printf("%d \n",a[i]);
}

b=testfunc(a,npts);

printf("returned array \n");
for (i=0; i<npts; i++)
{
printf("%d \n",b[i]);
}
}
printf("the size of one integer is %d \n",sizeof(int));

return 0;
}
int* testfunc(int *b,int npts)
{
int *c;
int i=0;

c=(int *) malloc(sizeof(int)*npts);

for (i=0; i<npts; i++)
{
c[i]=b[i]+10;
}

return c;
}

这是避免在函数内部分配内存并能够多次调用该函数的可能解决方案

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

void testfunc(int *c,int *d,int npts);

int main(int argc, char* argv[])
{
int *a,*b;
int i,j,npts=10;

a=malloc(sizeof(int)*npts);
b=malloc(sizeof(int)*npts);

for (j=0; j <100; j++)
{
printf("iteration number %d \n",j);
for (i=0; i<npts; i++)
{
a[i]=i;
printf("%d \n",a[i]);
}

testfunc(a,b,npts);

printf("returned array \n");
for (i=0; i<npts; i++)
{
printf("%d \n",b[i]);
}
}
printf("the size of one integer is %d \n",sizeof(int));

free(a);
free(b);

return 0;
}
void testfunc(int *c,int *d,int npts)
{
int i=0;

for (i=0; i<npts; i++)
{
d[i]=c[i]+10;
}
}

最佳答案

c=(int *) malloc(sizeof(int)*npts);
:
return c;

这会将内存管理它的责任交还回去。

完成后释放它已成为调用者(本例中的 main)的责任。

真正的问题出在 main 中:

b=(int *) malloc(sizeof(int)*npts);
:
for (some number of iterations)
b=testfunc(a,npts); // overwrites b

在那个“覆盖”行,你实际上有一个内存泄漏,因为你失去了对当前分配给 b 的内存的访问权(在循环的最初和之前的迭代中)。


另外,请不要在 C 中强制转换 malloc 的返回值。这不是必需的,并且可以隐藏某些您确实不会 需要调试 :-)

关于c - 如果您不释放函数中动态分配的内存,会发生什么情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24928460/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com