Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C memory allocation and deallocation

I have written the following C function that returns a double pointer after necessary memory allocation.

// integer double pointer to 2d array
void** idp_to_2d ( int rows , int cols ) {
    int i ;
    void **est = malloc ( rows * sizeof ( int* ) ) ;
    for ( i = 0 ; i <= rows ; i ++ )
        est[i] = malloc ( cols * sizeof (int ) ) ;
    return est ;
}

Then I receive this pointer using the following code from main():

int **est = ( int** ) idp_to_2d ( rows , cols ) ;

It works fine and I can index like est[i][j] meaning memory was allocated correctly.

Now I free up the memory in main() using the code that follows:

int i ;
for ( i = 0 ; i <= rows ; i ++ )
    free ( est[i] ) ;
free ( est ) ;

Now I get double free or corruption error.

My compiler is gcc 4.9.2, OS is Ubuntu 15.04 (64-bit) and I am using NetBeans IDE 8.0.2.

like image 567
ashubuntu Avatar asked Dec 20 '22 04:12

ashubuntu


1 Answers

Your for loops are wrong - you are iterating over one too many rows - change:

for ( i = 0 ; i <= rows ; i ++ )
               ^^^

to:

for ( i = 0 ; i < rows ; i ++ )
               ^^^

in both the malloc loop and the free loop.


Also, although it's not a bug as such, you should really change:
void** idp_to_2d(...

to:

int** idp_to_2d(...

and of course:

void **est = malloc(...

to:

int **est = malloc(...

since the function returns an int ** not a void **. (There really is no point in using void ** in any of your code.)

You can also drop the redundant (and potentially dangerous) cast of the return value, so:

int **est = ( int** ) idp_to_2d ( rows , cols ) ;

would just be:

int **est = idp_to_2d ( rows , cols ) ;
like image 119
Paul R Avatar answered Jan 09 '23 15:01

Paul R