[英]C++ program ends for no reason ? (Hash table)
我正在嘗試使用單獨的鏈沖突解決方案來實現哈希表,但是我遇到了問題。 這是我的代碼(為簡化起見,做了一些修改,但錯誤仍然相同):
#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;
}
當我運行.exe文件(或從cmd開始)時,程序最終顯示消息app.exe已停止工作。 我嘗試調試程序並得到以下消息: http : //imgur.com/a/yOhRV
誰能幫我解決這個問題? 我已經發現問題一定是在insert()函數中,可能是在這種情況下,但是我不知道出什么問題了。
您取消引用指針而不檢查它: if (list->head == NULL)
...
您在這里執行的操作是獲取list
並檢查它所指向的值是否為NULL
,但是由於您尚未檢查if (list)
所以有可能list == NULL
並在取消引用時導致segfault
您正在聲明List* table[12]
但從未初始化。 因此它確實包含垃圾。
您必須執行以下操作才能對其進行初始化: List* table[12] = {NULL}
;
作為一般規則,您的代碼中永遠不要包含未初始化的變量(除非出於確切目的而最優化的目的)。
將默認構造函數添加到您的結構中,並使用初始化列表。 還要使變量盡可能局部(在循環內移動索引)。
您不需要ascii(),因為char是整數類型。 char + char和char * int被提升為int。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.