How to use malloc correctly in c and handle 0xc0000005 runtime error?

-2

I am trying to make a minesweeper game as homework in C. I am creating two 'arrays' using the malloc function.

The Problem:
The program runs until its end but terminates with code '0xc0000005' instead of 0. Looked it up and understood there's a problem with my malloc use.

note: the pointer *flags is not yet used in the function 'InitBoards'.

int main(){

char *board,
       *flags;

if((board = (char *)malloc(size* size)) == NULL || (flags = (char *)malloc(size * size) == NULL)){
        return -1;
    }
    intialized = InitBoards(&board, &flags, bombNum, size);
    if(!intialized){
        printf("Error in initialization");
        return -1;
    }
free(board);
free(flags);

return 0;
}
int InitBoards(char** board, char** flags, int bombNum, int size){

    int random,
        countBombs = 0,
        bombRow,
        bombCol,
        i,
        j;


    for(i = 0; i < size; i++){
        for(j = 0; j < size; j++){
            countSquare = 0;
            if(*(board + i * size + j) !=(char*) 'X'){
               *(board + i * size + j) = (char*)(48 + countSquare);
            }


        }
    }
    return 1;
}

I expect the exit code of the program to be 0 and not 0xc0000005. Maybe the problem is in my OS, Windows 10?

c
pointers
malloc
runtime-error
asked on Stack Overflow May 9, 2019 by gursik • edited May 9, 2019 by Jason Aller

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0