Reputation: 767
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()
?
Upvotes: 4
Views: 89
Reputation:
Yes,when your function finishes, you will lose the pointer to the allocated memory to free() it.
Upvotes: 3
Reputation: 134286
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.
Upvotes: 7