예외가 throw됨: 읽기 액세스 위반입니다. head이(가) nullptr였습니다.
조회수 4468회
include
typedef struct node { int value; struct node* next; } node; int ll_has_cycle(node* first) { node* head = first; while (head->next) { head = head->next; if (head == first) return 1; } return 0; } void test_ll_has_cycle(void) { int i; node nodes[5]; for (i = 0; i < sizeof(nodes) / sizeof(node); i++) { nodes[i].next = NULL; nodes[i].value = i; } nodes[0].next = &nodes[1]; nodes[1].next = &nodes[0]; nodes[2].next = &nodes[3]; printf("Checking first list for cycles. There should be a cycle, ll_has_cycle says it has % s cycle\n", ll_has_cycle(&nodes[0]) ? "a" : "no"); printf("Checking length-zero list for cycles. There should benone, ll_has_cycle says it has % s cycle\n", ll_has_cycle(NULL) ? "a" : "no"); printf("A node value is: %d", nodes[1].value); } int main(void) {
test_ll_has_cycle();
return 0;
} 코드를 실행해보니 예외가 throw됨: 읽기 액세스 위반입니다. head이(가) nullptr였습니다. 라고 뜨고 segmentation_fault라고 뜨네요 왜이러는거죠 ? ㅠㅠ
-
(•́ ✖ •̀)
알 수 없는 사용자
1 답변
-
ll_has_cycle(NULL)
라는 부분이 실행될때,while (head->next)
에서 에러가 발생하는 겁니다. head가 NULL이면 next에 접근할 수 없기 때문에 발생하는 에러입니다.head가 NULL이 아닐때에만
head->next
에 접근하도록 수정해주세요.아래 코드 참고하세요.
- 코드
#include<stdio.h> typedef struct node { int value; struct node* next; } node; int ll_has_cycle(node* first) { node* head = first; if (head != NULL) { while (head->next) { head = head->next; if (head == first) return 1; } } return 0; } void test_ll_has_cycle(void) { int i; node nodes[5]; for (i = 0; i < sizeof(nodes) / sizeof(node); i++) { nodes[i].next = NULL; nodes[i].value = i; } nodes[0].next = &nodes[1]; nodes[1].next = &nodes[2]; nodes[2].next = &nodes[3]; nodes[3].next = &nodes[4]; nodes[4].next = &nodes[0]; printf("Checking first list for cycles. There should be a cycle, ll_has_cycle says it has % s cycle\n", ll_has_cycle(&nodes[0]) ? "a" : "no"); printf("Checking length-zero list for cycles. There should benone, ll_has_cycle says it has % s cycle\n", ll_has_cycle(NULL) ? "a" : "no"); printf("A node value is: %d", nodes[1].value); } int main(void) { test_ll_has_cycle(); return 0; }
- 결과
-
(•́ ✖ •̀)
알 수 없는 사용자
댓글 입력