Consider the following function:
void free_or_not ( int count ) {
int i ;
int *ip = malloc ( count * sizeof ( int ) ) ;
for ( i = 0 ; i < count ; i ++ )
ip[i] = i ;
for ( i = 0 ; i < count ; i ++ )
printf ( "%d\n" , ip[i] ) ;
free ( ip ) ;
}
Will this cause memory leak if I don't call free()
inside free_or_not()
?
Will this cause memory leak if I don't call
free()
insidefree_or_not()
?
Yes, it will cause memory leak. Once your function finishes execution, you don't have any pointers to the allocated memory to free()
it.
Solution: If you change the return type of your function to void *
(or similar) and return the allocated pointer (ip
)from the function, then, you can collect that pointer tn the caller and free()
the pointer from the caller of this function.
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