2017-05-15 1 views
0

별도의 체인 충돌 해결로 해시 테이블을 구현하려고하는데 문제가 있습니다. 작동이 중지되었습니다 App.exe가 그 나는 .exe 파일을 실행 (또는 cmd를에서 시작) 때C++ 프로그램이 아무 이유없이 종료됩니까? (해시 테이블)

#define _CRT_SECURE_NO_WARNINGS 
#include <iostream> 
#include <fstream> 
#include <cstring> 
#include <string> 
using namespace std; 

int ascii(char character) 
{ 
    return character; 
} 

int hashFunction(string word, int num) 
{ 
    char* str = new char[word.length() + 1]; 
    strcpy(str, word.c_str()); 
    return ((3 * ascii(str[0]) + 5 * ascii(str[1]))) % num; 
} 

typedef struct tab 
{ 
    string data; 
    struct tab* next; 
}Node; 

typedef struct link 
{ 
    Node* head; 
    Node* tail; 
}List; 

List* createList() 
{ 
    List* list = new List(); 
    if (list) 
    { 
     list->head = NULL; 
     list->tail = NULL; 
    } 
    return list; 
} 

void insert(List* list, string data) 
{ 
    //if list is empty 
    if (list->head == NULL) //!!!!!!!!!!!!!!!!ERROR OCCURE HERE !!!!!!!!!!!!!!! 
    { 
     list->head = new Node(); 
     list->head->data = data; 
     list->head->next = NULL; 
     list->tail = list->head; 
    } 
    //if list already contains some data 
    else 
    { 
     list->tail->next = new Node(); 
     list->tail->next->data = data; 
     list->tail = list->tail->next; 
     list->tail->next = NULL; 
    } 
} 

int main(int argc, char* argv[]) 
{ 
    int size = 8; //Size of hash table (number of indexes) 

    List* table[12]; 

    string A[8] = {  "hello","world","car","notebook","science","starwars","lollypop","anything" }; 

//Insert elements from array A into a hash table 
int index; 
for (int i = 0; i < size; i++) 
{ 
    index = hashFunction(A[i], size); 
    if (table[index] == NULL) 
     table[index] = createList(); 
    insert(table[index], A[i]); 
} 

return 0; 
} 

, 프로그램이 메시지와 함께 끝 : 이것은 (아직 조금 단순화하도록 수정하지만, 오류 같은) 내 코드입니다 . 나는 프로그램을 디버그 해보고 이것을 가지고 : http://imgur.com/a/yOhRV

아무도 도와 줄 수있는 방법이 문제를 해결할 수 있습니까? 나는 문제가 insert() 함수에 있어야한다고 생각했는데, 아마도 조건에 있지만, 나는 무엇이 잘못되었는지 모른다.

당신이 list을 복용하고 그것을 가리키는 값이 NULL 경우 cheking되고, 여기서 뭐하는거야 ... if (list->head == NULL),하지만 당신은 if (list)을 선택하지 않았기 때문에 다음이다 :

+2

스택 오버플로에 오신 것을 환영합니다! [디버거] (https://en.wikipedia.org/wiki/Debugger)를 사용하여 코드를 단계별로 실행하는 방법을 배워야 할 필요가있는 것 같습니다. 좋은 디버거를 사용하면 한 줄씩 프로그램을 실행하고 예상 한 곳에서 벗어난 곳을 볼 수 있습니다. 프로그래밍을 할 때 필수적인 도구입니다. 추가 읽기 : [작은 프로그램을 디버깅하는 방법] (https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). –

답변

3

당신은 그것을 확인하지 않고 포인터를 derefernce 가능하다면 list == NULL이고 역 참조시 segfault가 발생합니다

1

List* table[12]을 선언했지만 초기화되지 않았습니다. 그래서 그것은 쓰레기를 포함합니다.

초기화하려면 다음을 수행해야합니다. List* table[12] = {NULL};

0

일반적으로 코드에서 초기화되지 않은 변수가 없어야합니다 (수행하려는 작업을 정확히 알고있을 때 최적화를위한 경우 제외).

기본 생성자를 구조체에 추가하고 초기화 목록을 사용하십시오. 또한 가능한 한 로컬 변수를 유지하십시오 (루프 내부의 인덱스 이동).

ascii()가 필요하지 않습니다. 원인 char는 정수 유형입니다. char + char 및 char * int는 int로 승격됩니다.

관련 문제