我在书中了解到,如果我需要从函数返回指针,我会使用malloc()并从堆中获取内存.我想知道如何free()在函数后分配内存.
可以做我在下面的代码中做的事情来释放那个内存吗?如果它不正确,在功能后释放内存的正确方法是什么?
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;
}
Run Code Online (Sandbox Code Playgroud)