c - CrtIsValidHeapPointer error when trying to free an element of a linked list -
my program crashes error related invalid heap pointer. in first function allocate 5 cells , point "snake_head" first element in list, , "snake_tail" points last element. in second function try free last element list, , move snake_tail next cell in list. went wrong while freeing snake_tail. don't understand is.
#include <stdio.h> #include <stdlib.h> typedef struct pos_s { unsigned int x; unsigned int y; }pos_t; typedef struct snake_cell_s { pos_t pos; struct snake_cell_s* next; // struct snake_cell_s* prev; } snake_cell_t; void init_snake(snake_cell_t** snake_head, snake_cell_t** snake_tail) { int i; const int init_snake_size = 5; unsigned int init_snake_x = 5; unsigned int init_snake_y = 5; *snake_head = (snake_cell_t*)malloc(sizeof(snake_cell_t)*init_snake_size); snake_cell_t* snake_cell[init_snake_size]; (i = 0; i<init_snake_size; ++i) { snake_cell[i] = (*snake_head) + i; snake_cell[i]->pos.x = init_snake_x + i; snake_cell[i]->pos.y = init_snake_y; if (i<init_snake_size - 1) { snake_cell[i]->next = *snake_head + + 1; } else { snake_cell[i]->next = null; } } *snake_tail = snake_cell[init_snake_size - 1]; (*snake_tail)->next = null; } snake_cell_t* advance_snake_tail(snake_cell_t* snake_head, snake_cell_t* snake_tail) { snake_cell_t* snake_new_tail; snake_cell_t* snake_cell = snake_head; while (snake_cell->next->next != null) { snake_cell = snake_cell->next; } snake_new_tail = snake_cell; snake_new_tail->next = null; free(snake_tail); // < ---- crash happens here return snake_new_tail; } int main() { snake_cell_t* snake_head = null; snake_cell_t* snake_tail = null; init_snake(&snake_head, &snake_tail); // create 5 cell snake list snake_tail = advance_snake_tail(snake_head, snake_tail); // update snake tail- remove last cell , move pointer previous cell return 0; }
you're free
ing pointer not returned malloc
. – immibis
Comments
Post a Comment