0
내 프로그램이 잘못된 힙 포인터와 관련된 오류로 인해 충돌합니다. 첫 번째 함수에서는 5 개의 셀을 할당하고 목록의 첫 번째 요소에 "snake_head"를 지정하고 "snake_tail"은 마지막 요소를 가리 킵니다. 두 번째 함수에서 목록의 마지막 요소를 해제하고 snake_tail을 목록의 다음 셀로 이동합니다. snake_tail을 해제하는 동안 문제가 발생했습니다. 나는 그것이 무엇인지 이해하지 못한다.링크 된 목록의 요소를 해제하려고 할 때 CrtIsValidHeapPointer 오류가 발생했습니다.
#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;
}
디버거가 뭐라고 말 했나요? –
디버그 어설 션이 실패했습니다! 프로그램 : ... 15 \ 프로젝트 \의 ConsoleApplication1 \ 디버그 \되는 ConsoleApplication1.exe 파일 : minkernel의 \ 브라운관 \ ucrt \ SRC \ appcrt \ 힙 \의 debug_heap.cpp 라인 : 888 식 : _CrtIsValidHeapPointer (블록) 당신이있어 – sergeyrar
'malloc'에 의해 리턴되지 않은 포인터를'free '합니다. – immibis