10

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;
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
shinhwa
  • 129
  • 1
  • 4

2 Answers2

9

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.

  1. Please see why not to cast the return value of malloc() and family in C.
  2. Always check for the success of 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.

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
4

This is generally considered poor program design. The module that does the malloc() should be designed so that it is also responsible for doing the free().

You should never design programs so that some external routine is supposed to clean up the mess from your module. It is all common sense really.

So in this case, you should add a wrapper function around free(), which main() can call. main() shouldn't need to know or care about how your routines perform dynamic allocation/deallocation.

Note that programs that don't follow this program design tend to have memory leak-related bugs.

Lundin
  • 195,001
  • 40
  • 254
  • 396
  • Well said, also I think there has been one issue left out. – Sumeet Aug 19 '15 at 14:30
  • 1
    @Sumeet Dangling pointers is only an issue if the routines are expected to be called yet again with the same inputs. In that case, it is up to the routines which do the malloc/free to handle it. – Lundin Aug 19 '15 at 14:44
  • But still making it NULL is a good thing to do, don't you think. – Sumeet Aug 19 '15 at 14:48
  • 1
    @Sumeet It entirely depends on the nature and functionality of the code. It might be very good and necessary, or it might be superfluous clutter. – Lundin Aug 19 '15 at 14:49