I am programming the classic Snake game in C using doubly linked lists and have written a function that creates a pointer, allocates the required space for the structure, then allocates memory for the next pointer in the list and so on. In the end the pointer to the first element is returned by the function and can be assigned to the head pointer in the main function.
When starting the game I want the snake to have a length of three so I had three malloc's in the function and used pointer, pointer->next, pointer->next->next and so forth and everything was working.
Since a lot of steps have to be repeated in this process I thought of putting all of this into a for-loop like this:
#include <stdio.h>
#include <stdlib.h>
typedef struct snake snake;
struct snake {
int x; /* x coordinate */
int y; /* y coordinate */
snake *previous;
snake *next;
};
snake *initSnake(void) {
snake *pointer, *tmp1, *tmp2 = NULL;
/* three iterations, so the snake will have a length of three */
for( int i = 0; i<3; i++, tmp1 = tmp1->next) {
if(NULL == (tmp1 = (snake*)malloc(sizeof(snake)))) {
return NULL;
}
/* coordinates */
tmp1->x = 20;
tmp1->y = 10 + i;
/* first previous points to NULL */
tmp1->previous = tmp2;
/* temporarily store last pointer to be used for next previous pointer */
tmp2 = tmp1;
if(0 == i) {
/* store first pointer so it can be returned */
pointer = tmp1;
}
}
/* the last next pointer has to point to NULL */
tmp1 = NULL;
/* now return the pointer to the first element in list */
return pointer;
}
int main() {
/* pointer to first element in list */
snake *head = NULL;
if(NULL == (head = initSnake() ) ) {
fprintf(stderr, "Not enough memory!\n");
return EXIT_FAILURE;
}
/* here everything works fine */
printf("%d\n", head->y);
printf("%d\n", head->previous);
/* when trying to acces the content of the next element, the program crashes... */
printf("%d\n", head->next->x);
/* pause */
getchar();
}
The problem is that when I try to access the second element of the list inside the main function, the game crashes. I suspect that something is wrong with
tmp1 = tmp1->next
in the for-loop and I don't really access the next pointers but I am not completely sure.
Can you help me out?