I made a snake program with Linked List, the program is working but I have some warning, I wonder if I did something wrong or its just something to ignore.The program itself working without any bugs.
I
//Thats what I send from main
SNAKE* snake = (SNAKE*)malloc(sizeof(SNAKE));
//Thats the function
void initialSnaKE(SNAKE* snake){
NODE* tail = (NODE*)(malloc(sizeof(NODE)));
NODE* head = (NODE*)(malloc(sizeof(NODE)));
head->prev = NULL;
tail->prev = head;
head->next = tail;
tail->next = NULL;
head->x = ROWS / 2;
head->y = COLS / 2;
snake->head = head;
snake->tail = tail;
}
There are chances that malloc
may fail, that is what compiler is complaining. You have to have proper NULL
checks before dereferencing the pointers.
void initialSnaKE(SNAKE* snake){
if (!snake) return; //invalid input
NODE* tail = (NODE*)(malloc(sizeof(NODE)));
if (!tail) return; //allocation failed.
NODE* head = (NODE*)(malloc(sizeof(NODE)));
if (!head) {
free(tail);
return;
}
head->prev = NULL;
tail->prev = head;
head->next = tail;
tail->next = NULL;
head->x = ROWS / 2;
head->y = COLS / 2;
snake->head = head;
snake->tail = tail;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.