C++传递指针数组到函数时出现Segmentation fault(段错误)问题求助
哈希表段错误修复方案
核心错误点
- 哈希表类型定义错误:分离链接法要求哈希表存储链表头指针,你当前定义的是
Node对象数组而非Node指针数组,后续指针访问逻辑完全错位,且未对数组元素初始化,next指针为野指针,直接访问必然触发段错误。 - 链表遍历逻辑错误:
insert函数中while循环退出时indexPtr已经是nullptr,此时直接访问indexPtr->next属于空指针解引用,直接触发段错误。 - 传参类型不匹配:你定义的
hashTable是Node*类型,取地址传入后参数table拿到的是指向单个指针的地址,table[下标]访问时会直接越界。 Node结构体成员未完全初始化:next指针没有默认初始值,创建节点时容易产生野指针。
具体修复步骤
- 修正
Node结构体定义,给next指针加默认初始值
struct Node { unsigned int hash = 0; string word; int count; Node* next = nullptr; // 新增默认初始化 };
- 修正哈希表定义,改为指针数组并初始化所有元素为
nullptr
// 原错误写法 // Node* hashTable = new Node[TABLE_SIZE]; // 修复后写法 Node** hashTable = new Node*[TABLE_SIZE]();
- 修正
insert函数的遍历逻辑,循环终止时停在链表最后一个非空节点上
int insert(unsigned int hash, string word, Node* table[]) { unsigned int hashIndex = hash % TABLE_SIZE; // 提前取模避免重复计算 Node* newNode = new Node(); newNode->hash = hash; newNode->count = 1; newNode->word = word; newNode->next = nullptr; if(table[hashIndex] == nullptr) { table[hashIndex] = newNode; return 0; } else { Node* indexPtr = table[hashIndex]; while(indexPtr) { if(indexPtr->hash == hash) { indexPtr->count++; delete newNode; // 匹配到重复单词,要释放提前创建的新节点避免内存泄漏 return 2; } if(!indexPtr->next) break; // 到链表尾部就跳出循环 indexPtr = indexPtr->next; } indexPtr->next = newNode; } return 1; }
- 修正
insert调用传参,直接传哈希表指针数组本身即可
// 原错误写法 // insert(hash, word, &hashTable); // 修复后写法 insert(hash, word, hashTable);
内容的提问来源于stack exchange,提问作者Flip The Ewok
相关产品推荐
相关产品推荐

