c - "malloc in local function, free memory in main" is it ok? How? -
this question has answer here:
i learned in book if need return pointer function, use malloc()
, memory heap. wondering how can free()
memory allocated after function.
is ok did in following code free memory? if it's not correct, what's correct way 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, code correct.condition apply, see note below
to free()
allocated memory, need pass returned pointer malloc()
, family.
as you're getting same pointer returned malloc()
add_them_up ()
function , storing same in presult
, in main()
, can call
free (presult);
without issues. carry out intended job.
note: you're missing 2 aspects here, e.g.
- please see why not cast return value of
malloc()
, family inc
. - always check success of
malloc()
before using returned pointer.
that said, suggestion, try use form
int *p = malloc(sizeof(*p));
which makes allocation statement independent of type of p
, resulting in robust code.
Comments
Post a Comment