Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"malloc in local function, free memory in main" is it ok? How? [duplicate]

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;
}
like image 886
shinhwa Avatar asked Aug 19 '15 13:08

shinhwa


1 Answers

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.

like image 171
Sourav Ghosh Avatar answered Nov 15 '22 19:11

Sourav Ghosh