I'm recently working on simple chess game on the terminal using C, but I've ran into a small issue in regard to taking user input.
The following function takes in a 3-Dimensional array containing current chess piece placements, a pointer to a buffer that'll contain the user input, and the size of this buffer which I set to 7.
void next_move(char board[8][8][4], char* move, size_t buff_size){
char * move_1 = (char )malloc(sizeof(char)3);
char * move_2 = (char )malloc(sizeof(char)3);
char delim[]=" ";
getline(&move,&buff_size,stdin);
move_1=strtok(move,delim);
move_2=strtok(NULL,delim);
if(*move_1 == '\0'){
printf("invalid move !");
return ;
}
printf("%s%s\n",move_1,move_2);
if(!check_move(board, move_1, move_2)){
printf("valid move !\n");
}
}
The function check_move takes in both moves inputted by the user and verifies if they're valid chess moves (E.g "Nb1 Nc3").
My issue lies in the fact that when the user inputs no character or a string of characters not containing a space (the delimeter defined in strtok) it results in a segmentation fault when I try to do the check:
if(*move_1 == '\0')
Which is used mainly to handle the exception in the case that the move_1 and move_2 pointers are null.
I have two questions:
- How can I check if a char pointer is null ? (I have already tried using
move_1 == NULL)
- Why the does the code continue execution and returns if I set the conditional statement to
if(*move_1 != 0)
. Although this causes all input (even if it's the correct format) to not be valid.