You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++链表重复检测函数detect_duplicates触发core dump段错误的原因是什么

段错误触发原因及修复方案

段错误的核心原因是detect_duplicates函数存在空指针访问问题,具体错误点如下:

  • 循环越界导致temp变为空指针
    for循环一共执行size次,当执行到最后一轮(i = size - 1)时,temp已经指向链表最后一个节点,执行temp = temp->next后temp会被赋值为NULL,接下来执行temp2 = temp后temp2也为NULL,while循环判断temp2->next != NULL时,尝试访问空指针的成员变量,直接触发段错误。
  • 内层循环判断逻辑错误
    当前内层循环的终止条件为temp2->next != NULL,会导致链表最后一个节点的data永远不会被比较,就算修复空指针问题也会漏检重复元素。

修复后的detect_duplicates函数代码

void detect_duplicates(struct node* head, int size)
{
    int x, y;
    struct node *temp, *temp2;
    temp = head;
    cout << "Duplicate elements are : ";

    // 外层循环只需要遍历到倒数第二个节点即可
    for (int i = 0; i < size - 1; i++) {
        x = temp->data;
        temp2 = temp->next;
        // 内层循环判断temp2本身不为空即可,覆盖所有后续节点
        while (temp2 != NULL) {
            y = temp2->data;
            if (x == y) {
                cout << y << " ";
            }
            temp2 = temp2->next;
        }
        // 移动temp放到最后,避免提前变成空指针
        temp = temp->next;
    }
}

修复后可正常输出重复元素:1 2 4。

如果需要优化性能,可以额外使用哈希表存储已出现的元素,单次遍历即可完成检测,时间复杂度从O(n²)降低到O(n)。

内容的提问来源于stack exchange,提问作者Alex Baby

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 02:21:00