Hello!
I am programming the 4 in line game, and I've been getting a segmentation fault error that I'm not being able to correct. I've read dozens of posts and still didn't get it.
Please bare with me with this problem.
I've been able to narrow the problem to the following routine:
After human player makes move, computer generates random move. For each random move it generates, the program checks if the move is valid (If there are no empty cells bellow). For him to do that, I made a function that converts the column in question to a string.
Here is the code of the 3 functions.
Code:
char * ColGameToStr (jogo_4line * jg, int numcol)
{
int i, n;
i=numcol;
if (i>47 && i<56) i = numcol-48-1;
char *str = malloc (sizeof (char) * 7);
if(!str)
{return NULL;
exit(0);}
for (n = 0; n < 6; n++)
{
str[n] = jg->T[n][i];
}
str[n] = '\0';
return(str);
}
Code:
int CheckMove (char * move, int player, jogo_4line * jg)
{
char * colstr = malloc(sizeof(char)*6+1);
char *colaux=colstr;
int n;
colaux=ColGameToStr(jg,move[2]);
colaux[7]='\0';
for (n=move[0]-48-1-1; n>=0;n--)
{
if (colaux[n]==EMPTY)
{ free(colstr);
return 0;
}
}
free(colstr);
return 1;
}
Code:
void GenerateMove (jogo_4line * jg)
{
char line, col;
srand48 (time (NULL));
line=drand48()*6+49;
col=drand48()*7+49;
char play[]={line,',',col};
if (jg->T[line-1-48][col-1-48]==EMPTY && CheckMove(play, jg->turn, jg))
{
jg->T[line-48-1][col-48-1]=COMPUTER;
jg->turn=1;
}
else GenerateMove(jg);
Additional information:
jogo_4line is the following struct:
Code:
typedef struct {cell T[6][7]; int turn; int endgame;} jogo_4line;
The T[6][7] represents each cell of the board.
COMPUTER and EMPTY are macros that represent a state of a cell. EMPTY=' ', COMPUTER='X' .
When GenerateMove happens to find a valid move quickly, the segmentation fault doesnt happen, only if the functon GenerateMove calls itself a certain amount of times.
I think the problem is in the ColGameToStr function, but I'm really unable to find a solution for this