我的程序因与无效堆指针相关的错误而崩溃。 在第一个函数中,我分配5个单元格并用“snake_head”指向列表中的第一个元素,“snake_tail”指向最后一个元素。 在第二个函数中,我尝试从列表中释放最后一个元素,并将snake_tail移动到列表中的下一个单元格。 解冻snake_tail时出了点问题。我不明白它是什么。
#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];
for (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 + i + 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 a 5 cell snake list
snake_tail = advance_snake_tail(snake_head, snake_tail); // update snake tail- remove last cell and move pointer to previous cell
return 0;
}
答案 0 :(得分:0)
您{{}} free
malloc
未返回的指针。 - immibis