Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will malloc automatically free the memory at the end of a function?

Tags:

c

I would be very glad if someone could help me in understanding completely the differences between the following codes:

// Code (1)
void f1 ( void ){
  int * ptr1 = malloc ( sizeof(int) );
}

and

// Code (2)
void f2 ( void ){
  int * ptr2 = malloc ( sizeof(int) );
  free(ptr2);
}

As far I know, the instruction free is useful for deallocating the used memory, but on the other hand I know that every time we call a function g, if here there are new variables to be declared, they will be created and destroyed (i.e. deallocated, right?) after the execution of g.

Consequently:

do we need to use the instruction free in Code(2), or it is superfluous? (but maybe suggested for making the code more clear)

Thanks

Ps: you may be also interested in helping me with My previous related question. There, some users suggested to use the dynamic allocation of memory, and I am trying to understand why/how to.

like image 793
Biagio Avatar asked Oct 17 '25 14:10

Biagio


1 Answers

No. malloc will not free the allocated memory. You need to use free to free the allocated chunk.
It is also the case that at the end of the program (main function) the allocated memory automatically freed by the system, but better to free it explicitly.

Always remember that the lifetime of dynamically allocated memory is till the end of the program if it is not deallocated specifically.

like image 113
haccks Avatar answered Oct 20 '25 05:10

haccks