I’m working on a network programming project to write a client server Rock Paper Scissors code. I finished the code and it was working well during the tests before I add this line to the code.
findWinner(gameType,pcChoice);
when I added the line to the code the code started giving me an error about segmentation fault from the server side. this is the place that I added the line.
while(1)
{
int gameType;
printf("Paper, Scissors, Rock game start.\n");
rc = read(client_sockfd, &gameType, 1);
srand(time(NULL));
pcChoice = (rand() % 3)+1;
findWinner(gameType,pcChoice);
gameType = pcChoice;
write(client_sockfd, &gameType, 1);
}
I am an amature in C and dont know what to do.
int pcChoice;
it is an integer to keep a random integer from 1 to 3 (rock paper or scissors)
findwinner():
void findWinner(int player,int pc)
{
const char *items[3]={"Paper","Scissors","Rock"};
printf("Client: %s\n",items[player-1]);
printf ("Computer: %s\n",items[pc-1]);
switch (player)
{
case 1:
switch (pc)
{
case 1:
printf("it is a DRAW\n");
break;
case 2:
printf("Computer Wins\n");
break;
case 3:
printf("Computer Loses\n");
break;
default:
printf("ERROR\n");
exit(0);
};
break;
case 2:
switch (pc)
{
case 1:
printf("Computer Loses\n");
break;
case 2:
printf("it is a DRAW\n");
break;
case 3:
printf("Computer Wins\n");
break;
default:
printf("ERROR\n");
exit(0);
};
break;
case 3:
switch (pc)
{
case 1:
printf("Computer Wins\n");
break;
case 2:
printf("Computer Loses\n");
break;
case 3:
printf("it is a draw\n");
break;
default:
printf("ERROR\n");
exit(0);
};
break;
default:
printf("ERROR\n");
exit(0);
}
}
other things that might be problematic are:
Try to explicit null terminate the
char*Are you sure player is never negative or bigger than 3?