Jump to content

C two dimensional array segmentation fault

FakezZ
Go to solution Solved by Mr_KoKa,

You are assigning NULL to mem instead comparing it against NULL in the first if. The whole if condition evaluates to NULL so it is not fulfilled and doesn't return 1.

So I have a header file where I declare this: double **mem. Then in the C file where the function definitions are I have the following code which initializes the array.

int initMem(int x, int y){
    int i, j;
    mem = malloc(sizeof(double*) * x);
    if(mem = NULL){
        printf("Not enough memory\n");
        return 1;
    }
    for(i = 0; i < x; i++){
        mem[i] = malloc(sizeof(double) * y);
        if(mem[i] == NULL){
            printf("Not enough memory\n");
            return 1;
        }
    }
    for(i = 0; i < x; i++){
        for(j = 0; j < y; j++){
            mem[x][y] = -1;
        }
    }
    return 0;
}

The segmentation fault happens as soon as the first for loop starts in the first line. The function is called in main. What could be the cause of it?

MacBook Pro 15' 2018 (Pretty much the only system I use)

Link to comment
Share on other sites

Link to post
Share on other sites

You are assigning NULL to mem instead comparing it against NULL in the first if. The whole if condition evaluates to NULL so it is not fulfilled and doesn't return 1.

Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, Mr_KoKa said:

You are assigning NULL to mem instead comparing it against NULL in the first if. The whole if condition evaluates to NULL so it is not fulfilled and doesn't return 1.

omg i am stupid... Thanks I pulled an almost all nighter trying to debug this -_- 

MacBook Pro 15' 2018 (Pretty much the only system I use)

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×