OiO.lk Blog C++ malloc & free in C with multidimensional arrays in C; Whats wrong with the code
C++

malloc & free in C with multidimensional arrays in C; Whats wrong with the code


I am a beginner and i am working on a code where the multidim arrays are allocated with the malloc, malloc variant. I have to add an Array with a higher dimension (3D instead of 2D).

I discovered a strange behavior and i would be thankful for an explanation.

I know this is not really the proper way to handle multidimensional arrays. But it is already used in the program that i am modifying.

Thats a working code i used to isolate the problem in onlinegbd.com:

#include <stdio.h>
#include <stdlib.h>

double ***AllocArray3D(short ix, int iy, int iz){
    double ***A3D; ix++; iy++;
    A3D = (double ***)malloc(ix * sizeof(double **));
    int i, j;
    for (i = 0; i < ix; i++) {
        A3D[i] = (double **)malloc(iy * sizeof(double *));

        for (j = 0; j < iy; j++) {
            A3D[i][j] = (double *)malloc(iz * sizeof(double));
            if(!(j+1 < iy))printf("alloc i=%d,j=%d\n",i,j); //debug
        }
    }
    return A3D;
}

void FreeArray3D(double *** A3D, int ix, int iy){
    ix++; iy++;
    int i, j;
    for (i = 0; i < ix; i++) {
        for (j = 0; j < iy; j++) {
            if(!(j+1 < iy))
                printf("free i=%d,j=%d\n",i,j); //wenn das der letzte durchlauf ist printe
            free(A3D[i][j]);
        }
        free(A3D[i]);
    }
    free(A3D);
}

int main(){
    int a=99, b=99;
    double *** A_xyz;
    A_xyz = AllocArray3D(a, b, 1309);
    FreeArray3D(A_xyz, a, b);
    return 0;
}

when i change one function to(note the change in the condition of the for loops):

double ***AllocArray3D(short ix, int iy, int iz){
    double ***A3D;//x++; iy++;
    A3D = (double ***)malloc(ix * sizeof(double **));
    int i, j;
    for (i = 0; i < (ix+1); i++) {
        A3D[i] = (double **)malloc(iy * sizeof(double *));

        for (j = 0; j < (iy+1); j++) {
            A3D[i][j] = (double *)malloc(iz * sizeof(double));
            if(!(j+1 < iy))printf("alloc i=%d,j=%d\n",i,j); //debug
        }
    }
    return A3D;
}

or (note the change in the condition of the for loops):

double ***AllocArray3D(short ix, int iy, int iz){
    double ***A3D; x++; iy++;
    A3D = (double ***)malloc(ix * sizeof(double **));
    int i, j;
    for (i = 0; i <= ix; i++) {
        A3D[i] = (double **)malloc(iy * sizeof(double *));

        for (j = 0; j <= iy; j++) {
            A3D[i][j] = (double *)malloc(iz * sizeof(double));
            if(!(j+1 < iy))printf("alloc i=%d,j=%d\n",i,j); //debug
        }
    }
    return A3D;
}

I already checked that i can use the array and that every allocation is not NULL but the free() function is failing.

What did i miss? i would be very thankful for an explanation. Thanks in advance



You need to sign in to view this answers

Exit mobile version