Hi everyone, I have a mysterious problem with my program. I have narrowed it down to this code by using the debuger:
The problem with it seems to be that the second time through (there are / should be two items in the linked list) the pointer is garbage, but not NULL so it tries to call the move_snake function and therefore segfaults.Code:/* Loop through the snakes, moving them */
current_snake = first_snake;
while ( current_snake != NULL )
{
move_snake(current_snake);
current_snake = current_snake->next_snake;
}
Now I have the feeling that the bit of code there isn't the problem because it only crashes when the game tries to restart after a snake has crashed and not the first time its run, so I guess theres a problem with the function to remove all the snakes or with the function to add them again, although I have looked at them a lot and can't see a problem. Anyway here they are:
Hopefully its just a stupid mistake but I am totaly stuck trying to fix it! ThanksCode:void add_snake(Econtrol control,int x, int y)
{
struct snake *new_snake;
/* Allocate the memory and set the data */
new_snake = malloc(sizeof(struct snake));
new_snake->state = RIGHT;
new_snake->control = control;
/* Add two parts to the snake */
new_snake->first_part = NULL;
add_part(new_snake, x, y);
add_part(new_snake, x + 1, y);
/* Put the snake at the frount of the list */
new_snake->next_snake = first_snake;
first_snake = new_snake;
}
void remove_snakes()
{
struct part *current_part, *next_part;
struct snake *current_snake, *next_snake;
current_snake = first_snake;
first_snake = NULL;
while ( current_snake != NULL )
{
current_part = current_snake->first_part;
current_snake->first_part = NULL;
while ( current_part != NULL )
{
next_part = current_part->next_part;
free(current_part);
current_part = next_part;
}
next_snake = current_snake->next_snake;
free(current_snake);
current_snake = next_snake;
}
}