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;
}
Yes, your code is correct.condition apply, see note below
To free()
the allocated memory, you only need to pass the returned pointer from malloc()
and family.
As you're getting the same pointer returned by malloc()
back from the Add_them_up()
function and storing the same in presult
, in the main()
function you can call
free (presult);
without any issues. It will carry out the intended job.
Note: You're missing two aspects here, e.g.
malloc()
and family in C.malloc()
before using the returned pointer.That said, just a suggestion, always try to use the form
int *p = malloc(sizeof(*p));
which makes the allocation statement independent of the type of p
, resulting in a most robust code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With