Memory allocation and freeing memory

I wrote the following C function, which returns a double pointer after the 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 get this pointer using the following code from main():

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

It works fine, and I can index how est[i][j], because the memory has been allocated correctly.

Now I free the memory in main()using the following code:

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

Now I get a double free error or corruption .

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

+4
source share
1 answer

- - :

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

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

malloc, free.


, , :
void** idp_to_2d(...

int** idp_to_2d(...

, :

void **est = malloc(...

int **est = malloc(...

int ** a void **. ( void ** .)

( ) , :

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

:

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

All Articles