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.
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.
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