Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically allocate and free memory in local functions

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()?

like image 454
ashubuntu Avatar asked Dec 25 '22 19:12

ashubuntu


1 Answers

Will this cause memory leak if I don't call free() inside free_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.

like image 128
Sourav Ghosh Avatar answered Dec 28 '22 07:12

Sourav Ghosh