I learned in book that if I need to return a pointer from a function, I use malloc()
and get memory from the heap. I was wondering how I can free()
up the memory allocated after the function.
Is OK to do what I did in the following code to free that memory? If it's not correct, what's correct way to free memory after function?
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;
}