방금 내 프로그램에 세그먼트 오류가 있다는 오류 메시지가 표시되었습니다. 나는 gdb
을 사용하여 그것을 추적했으며 아래에서 그것을 발견했습니다. 어떻게 해결할 수 있습니까?C 프로그램 실행시 세그먼트 오류
void add_to_hash(HashTable **h, char *data)
{
int index = hash_value(data);
HashTable *curr_table = h[strlen(data)];
Node * exist_node = exist(curr_table, data);
if (exist_node == NULL)
{
Node *new_node = (Node*)malloc(sizeof(Node));
if (new_node == NULL) {
printf("Error allocating memory for new bucket\n");
exit(1);
}
if (data != NULL)
{
new_node->data = strdup(data);
new_node->next = curr_table->nodes[index];
curr_table->nodes[index] = new_node;
free(data);
}
}
else {
return;
}
}
//Rerturn the exist data.
Node* exist(HashTable* h, char* data)
{
int index = hash_value(data);
Node* list = NULL;
list = h->nodes[index];//gdb told me this line has error.
if (list) {
for (; list != NULL; list = list->next) {
if (strcmp(data, list->data) == 0) {
return list;
}
}
}
return NULL;
}
이것은 내가 그 라인이 오류가 gdb
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400baa in exist (h=0x0, data=0x644660 "a\n") at G1.c:129
129 list = h->nodes[index];
(gdb) bt
#0 0x0000000000400baa in exist (h=0x0, data=0x644660 "a\n") at G1.c:129
#1 0x0000000000400afa in add_to_hash (h=0x603250, data=0x644660 "a\n") at G1.c:105
#2 0x0000000000400920 in main (argc=3, argv=0x7fffffffebf8) at G1.c:55
그것은 확률이 낮다는 표시 한 선이 문제입니다 :
gdb
이exist
함수에 전달 된 매개 변수의 값을보고 있기 때문에 우리는 이것을 알고있다. 너의 질문에 gdb의 스택 추적을 붙여서 좁힐 수 있도록 도와야한다. 또한 크래시를 재현하는 작은 완전한 예제를 만드는 것을 고려해야합니다. –@RetiredNinja 죄송합니다. 편집했습니다. – Allen
'h = 0x0'. 너 한테 벨소리가 안 들니? 스택 추적을 시작하는 것은 좋은 출발이지만 변수 값을 검사하여 디버그 할 수 있습니다. 코드의 나머지 부분 (표시되지 않음)에 따라 여러 가지 방법으로 수정할 수 있습니다. 한가지 방법은'h'가'NULL'이라면 즉시'exist'에서 NULL을 반환하는 것입니다. 그러나 그것은 그 함수에 전달 될 때'h '가 NULL이 될 수 있는지에 따라 정확할 수도 있고 그렇지 않을 수도 있습니다. – kaylum