我在书中学到如果我需要从函数返回一个指针,我使用malloc()
并从堆中获取内存。我想知道如何在功能后分配内存。“本地函数中的malloc,主要空闲内存”可以吗?怎么样?
是否可以在下面的代码中执行以下操作来释放内存?如果它不正确,那么在函数之后释放内存的正确方法是什么?
int *Add_them_up (int *x, int *y)
{
int *p = (int *) malloc(sizeof (int));
*p = *x + *y;
return p;
}
int main()
{
int c = 3;
int d = 4;
int *presult = NULL;
presult = Add_them_up (&c, &d);
printf ("the result of adding is:%d\n", *presult);
free (presult);
return 0;
}
请查看[为什么不投射](http://stackoverflow.com/q/605845/2173917)'malloc()'和'C'中的系列的返回值。 –
@shinhwa有一个严重的问题,你在这里失踪。 –
@SouravGhosh你忽略了一个严重的问题我的朋友。 –