Search code examples
carraysmallocfreecorruption

double free or corruption 3d array in C


I get a 'double free or corruption' error while freeing up an 3d array. Can anyone please tell me where is the problem in the code? The size of the array is 2*N*N. Value of N here is 100. Even without casting, same result. Here is the code:

// Mallocing 
double ***h = malloc(2 * (sizeof(double**)));
for(i = 0; i < N; i++) {
    h[i] = malloc(N * sizeof(double*));
    for(j = 0; j < N; j++) {
        h[i][j] = malloc(N * sizeof(double));
    }
}

// Freeing
for(i = 0; i < N; i++) {
    for(j = 0; j < N; j++) {
        free(h[i][j]);
    }
    free(h[i]);
}
free(h);

The program works fine but at the end I get an error 'double free or corruption (!prev): 0x08cd24f8' Aborted (core dumped).


Solution

  • For the first dimension, you allocate 2 elements:

    double ***h = (double***) malloc(2 * (sizeof(double**)));
    

    But you treat it as if it had N elements:

    for(i = 0; i < N; i++) {
        h[i] = ...
    

    Change outermost loop comparison on allocation and free to:

    for(i = 0; i < 2; i++) {
    

    Also don't cast return value of malloc. Also, your code is missing error handling, and will break if allocation fails.