Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

4-dimensional array allocation: access violation

I wrote this simple piece of code to dynamically allocate a 4-dimensional array:

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

int**** alloc() {

    int i,j,k;
    int ****matrix;
    int x,y,z,n_pairs;

    x= 62;
    y= 45;
    z= 28;
    n_pairs = 4;

    matrix = (int ****) malloc(x*sizeof(int***));

    for (i=0; i<x; i++) {
        matrix[i] = (int ***) malloc(y*sizeof(int**));

        if(matrix[i]==NULL)
            return NULL;

        for (j=0; j<y; j++) {
            matrix[i][j] = (int **) malloc(z*sizeof(int*));

            if (matrix[i][j] == NULL)
                return NULL;

            for (k=0; k<n_pairs; k++) {
                matrix[i][j][k] = (int *)calloc(n_pairs,sizeof(int));

                if (matrix[i][j][k] == NULL)
                    return NULL;
            }
        }
    }

    return matrix;
}


void freeMatrix(int ****m) {

    int i,j,k;
    int x,y,z;

    x= 62;
    y= 45;
    z= 28;


    for(i=0; i<x; i++) {
        for(j=0; j<y; j++) {
            for(k=0; k<z; k++) 
                free(m[i][j][k]);

            free(m[i][j]);
        }

        free(m[i]);
    }

    free(m);
}

int main() {

    int i,j,k,h;
    int ****m = NULL;

    m = alloc();

    for(i=0;i<62;i++)
        for(j=0;j<45;j++)
            for(k=0;k<28;k++)
                for(h=0;h<4;h++)
                    printf("%d\t",m[i][j][k][h]);

    system("pause");

    return 0;
}

the problem is that I this code results in an Access Violation when I try to execute it. Isn't it the correct way to allocate/free a multidimensional array? If yes, then what is the problem?

like image 714
user1372813 Avatar asked Mar 05 '26 10:03

user1372813


1 Answers

One problem is here:

        for (k=0; k<n_pairs; k++) { //<----- This should read `k<z'
            matrix[i][j][k] = (int *)calloc(n_pairs,sizeof(int));

You probably meant to loop to z, not to n_pairs.

like image 175
NPE Avatar answered Mar 06 '26 22:03

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!