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.
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.
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 ) ;
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