단일연결리스트 에서 전체리스트를 삭제하는 함수인데 에러가뜨네요...
글쓴이: dlrudtlr2323 / 작성시간: 화, 2014/04/15 - 9:33오후
이게 전체 함수 작성한 내용입니다. 다른 함수들은 잘 작동하는데 항상 destroy함수만 실행하면 에러가뜨네요..
void destroy()함수는 전체 리스트를 삭제하고 메모리를 반납하는 함수입니다.
에러가 도대체 왜뜨는건지 모르겠네요... 빌드를 하면 실행창에서 작동이 중지되었다고 나오고...destroy함수만 그러네요
그리고 메인함수에서 system("pause"); 이거는 비주얼스튜디오2013을 사용해서 실행창을 보기위해 집어넣었습니다.
#include <stdio.h> #include <stdlib.h> typedef struct ListNode{ int data; struct ListNode *link; } ListNode; void init(ListNode *head) { head->data = 0; head->link = NULL; } void add(ListNode *head, int item) { ListNode *newNode; newNode = (ListNode*)malloc(sizeof(ListNode)); newNode->data = item; newNode->link = head->link; head->link = newNode; } void delete(ListNode *head, int item) { ListNode* cur = head; ListNode* deleteNode; int isRun = 0; while (cur->link != NULL) { if (cur->link->data == item) { isRun = 1; deleteNode = cur->link; cur->link = deleteNode->link; free(deleteNode); break; } cur = cur->link; } if (isRun == 0) printf("delete error: item %d값이 없습니다.\n", item); } void find(ListNode *head, int item) { int isRun = 0; ListNode *findNode = head; while (findNode != NULL) { if (findNode->data == item) { isRun = 1; return findNode; } findNode = findNode->link; } if (isRun == 0) printf("find error: item %d값이 없습니다.\n", item); } int length(ListNode *head) { ListNode *current = head; int count = 0; while (!isempty(current)) { current = current->link; count++; } printf("%d\n", count-1); return (count-1); } void destroy(ListNode *head) { ListNode *current = head; ListNode *temp; while (current != NULL) { temp = current; current = current->link; free(temp); } } int isempty(ListNode *head) { return head == NULL; } void display(ListNode *head) { ListNode *p = head->link; while (p != NULL) { printf("%d -> ", p->data); p = p->link; } printf("\n"); } int main() { ListNode *list1; list1 = (ListNode *)malloc(sizeof(ListNode)); init(list1); add(list1, 3); add(list1, 4); add(list1, 1); find(list1, 6); delete(list1, 2); length(list1); destroy(&list1); display(list1); free(list1); system("pause"); return 0; }
Forums:
destroy에서 포인터 주소를 넘기는 이유가 궁금하네요
main에 보면 destroy(&list1)에서 포인터변수 자체의 주소를 넘기고 있습니다. 그리고 이걸 수정한다 해도 뒤따라오는 display()랑 free()에서 에러가 다시 발생할테니 그것들도 지워야 될듯.
비주얼 스튜디오로 테스트한다면 그냥 곧바로 실행하지 마시고 디버깅 모드(F5)로 실행해보세요. 어디가 문제인지 금방 발견할 수 있습니다. 그냥 실행하면 다짜고짜 실행이 중단되는 것처럼 보이는 상황도 디버깅 모드로 실행하면 대부분 문제가 되는 곳에서 정확하게 브레이크가 걸립니다.
--
댓글 달기