How to fix memory allocation error (0xC0000005) when the array is passed to function

-2

I'm working with 1000x1000 array and I need to use malloc() for memory allocation. Everything was fine until I passed the array to a function.

I copy the code to test in the other file. I did exactly as I did to the main code except I didn't assign value to the array via the function.

here is my malloc in main function

double **z0 = (double **)malloc(sizeof(double *)*N);
    if (z0 == NULL){
        printf ("Cannot allocate memory\n");
    }
    for (i=0;i<N;i++){
        z0[i] = (double *)malloc(sizeof(double)*N);
        if (z0[i] == NULL){
            printf ("Cannot allocate memory\n");
        }
    }
init_matrix (F4, z0);
for (i=0;i<N;i++) free(z0[i]);
    free(z0);

the function init_matrix is defined as follow, in a separate header file

void init_matrix(double Func(double, double), double x[N][N]){
    int i,j;
    for (i=0;i<N;i++){
        for (j=0;j<N;j++){
            x[i][j] = Func(i, j); //f(y,x)
        }
    }
}

Also, this is the code that worked (I tested in the seperated file)

int main (void){
    int i, j;
    double **z0 = (double **)malloc(sizeof(double *)*N);
    if (z0 == NULL){
        printf ("Cannot allocate memory\n");
    }
    for (i=0;i<N;i++){
        z0[i] = (double *)malloc(sizeof(double)*N);
        if (z0[i] == NULL){
            printf ("Cannot allocate memory\n");
        }
    }

    for (i=0;i<N;i++){
        for (j=0;j<N;j++){
            z0[i][j] = (double)i;
        }
    }
    printf ("assigned value\n");
    for (i=0;i<N;i++){
        for (j=0;j<N;j++){
            printf ("%f ",z0[i][j]);
        }
        printf ("\n");
    }

    for (i=0;i<N;i++) free(z0[i]);
    free(z0);
}

Thank you

c
asked on Stack Overflow Apr 29, 2019 by PawatAka

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0