【问题标题】:C++ Segmentation fault in while loop when looking up values for a hash table查找哈希表的值时,while 循环中的 C++ 分段错误
【发布时间】:2016-10-30 20:46:16
【问题描述】:

我整个周末都断断续续地处理这个问题 - 试图找出我的 seg 故障发生在哪里。我已将其范围缩小到此功能,并认为我知道“为什么”会发生这种情况。段错误仅在执行查找时遇到哈希表中的 NULL 字段时发生。

表@@@ 输出中的@@@ 空值唯一一次出现在seg 故障之前——其他任何地方都没有。我在它之后有一个 continue 语句 - 甚至将 case 放在 while 循环中。怎么还是出错了? “下一个……”也永远不会出现。它只是在 @@ null 值 @@ 错误和 seg 错误之后结束。

有什么帮助吗?下面提供的代码

record *hashtable::lookup(keytype k)
{
    if (!table) return NULL;
    int i;
    int pos = hash(k, i = 0);
    if ((pos < 0) || (pos >= tsize)) return NULL;
    i = 0;
    while ((table[pos]->key != k && i < tsize) || (table[pos] == NULL && i < tsize))
    {
        cout << "next.." << endl;
        i++;
        pos = (hash(k, 0) + i*secondhash(k)) % tsize;
        if (table[pos] == NULL)
        {
            cout << "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@null value in table@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@" << endl;
            continue;
        }
        else {

        }
    }
    cout << "Got out of loop..." << endl;

    if (table[pos]->key == k) return table[pos];

    return NULL;
}

【问题讨论】:

  • 您的while 条件首先执行table[pos]-&gt;key,然后再验证table[pos] != NULL)。如果table[pos] == NULL,这会产生分段错误。
  • @Franck 哦,天哪。从外观上看你是对的。谢谢你,我不敢相信我已经为此工作了几个小时,却没有看到这一点。如果您想将其作为答案提交,我可以将此问题设置为已回答。

标签: c++ segmentation-fault hashtable


【解决方案1】:

问题可能在于您的while 循环。

条件首先访问table[pos]-&gt;key,即使table[pos] == NULL 可以是true,正如您的条件第二部分所建议的那样。这会在每次table[pos] == NULL 时创建一个分段错误。一个简单的解决方案是交换逻辑或的两个部分。

你可以替换

while ((table[pos]->key != k && i < tsize) || (table[pos] == NULL && i < tsize))

通过

while ((i < tsize) && ((table[pos] == NULL) || (table[pos]->key != k)))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-23
    • 2018-05-09
    • 2022-01-22
    • 1970-01-01
    • 2013-12-25
    • 2016-03-03
    相关资源
    最近更新 更多