Deallocating 2D array in C -
for whatever reason getting following error when trying free 2d array created:
error in `./a.out': free(): invalid next size (fast): 0x0000000001759310 *** aborted (core dumped)
i printed out contents of array , correct , able access of elements. however, yet able free it. error occurs when going through freeing loop, i.e. freeing double *. appreciate help.
thanks!
here code:
/*allocation*/ double **block_mat = (double **) malloc (sizeof(double *) * num_blocks); int i; (i = 0; <num_blocks; i++){ block_mat[i] = (double *) malloc (sizeof(double) * s); } /*freeing*/ (i = 0; < num_blocks; i++){ free(block_mat[i]); }
free(block_mat);
edit: error found! under-allocated memory...so when printed out arrays looked fine... allocated arrays of sizes s, used s^2 instead. thank everyone!
you allocate space s
doubles each block_mat[i]
. later, access
block_mat[i][block_index] = 0; block_index++;
but never check block_index
goes out of bounds, does.
if write beyond s
allocated doubles, might corrupt internal control data subsequent pointer, placed before pointer returned malloc
, required intact free
.
Comments
Post a Comment