C++ 链表 尾插入节点导致段错误

想请教一下各位,关于C++中的链表问题!!我学C学了俩学期,然后现在初入C++,啥啥都不懂,一个cai_niao
创建一个指针数组 struct X *List[100],用malloc分配内存,然后对于其中的某一个链表,比如 List[12] ,我想用一个同样类型的指针,struct X *temp, 去访问他,然后再这个链表的最后插入一个新节点,代码如下。
问题出在访问的过程中,因为要在链表末尾插入一个节点,所以先用循环让temp到达List的最后一个节点,但是,实际执行这个代码的时候,出现了段错误,看起来像是temp访问越界了。之前教C的时候我们都直接用这样的语法,Dev- C++不会报错,现在用VSCode他会报错了,我很不懂,求各位!超级感谢各位朋友!!

代码如下:

typedef struct bucket_node{
    int score;
    struct bucket_node* next;
}HashListNode;

HashListNode *List[100] = {(HashListNode*)malloc(sizeof(HashListNode))};
//声明结构体,创建链表

int hashCount(int score, int* grades, int N)
{
    int hashValue = score % 100;
    int count = 0;
    HashListNode* temp = List[hashValue];
**    while(temp->next != NULL){  //段错误出现在此处: temp->next!=NULL
**        if(temp->score == score){   
            count++;
        }
        temp = (HashListNode*)temp->next;
    }
    return count;
}

void insertHashNode(int score)
{
    int hashValue = score % 100;    //哈希值是成绩 % 20.
    HashListNode* node = (HashListNode*)malloc(sizeof(HashListNode));
    node->score = score;
    node->next = NULL;
    HashListNode* temp = List[hashValue];
**    while(temp->next != NULL){  //段错误出现在此处: temp->next!=NULL
**        temp = (HashListNode*)temp->next; //让temp处于链表的末尾
    }
    temp->next = node;    //将新产生的节点连接上去,这个节点就在此“桶”中。
}

引用 皆我百晓生 小程序回复内容作答:

问题出在你的链表初始化时,只分配了一个节点的内存空间,但是并没有将其指针赋值为NULL。所以在访问链表时,会出现段错误。

解决方法是在链表初始化时,将其指针赋值为NULL,表示链表为空。

修改代码如下:

HashListNode *List[100] = {NULL};

这样就可以避免段错误的问题了。

【以下回答由 GPT 生成】

解决方案:

段错误通常是由于访问了未经正确分配或释放的内存导致的。根据提供的代码,我发现存在几个需要修复的问题,可能导致段错误。下面是我对代码的一些修正和建议:

  1. 创建链表时,应使用循环为每个链表头节点分配内存,而不是仅分配一个节点。因为 struct X *List[100] 是一个指针数组,必须为每个指针分配内存。
  2. insertHashNode 函数中,需要特别注意处理链表为空的情况。在确定链表末尾位置后,应该首先判断 temp 是否为空,如果是,则将新节点直接插入链表头部。
  3. hashCount 函数中,应首先检查 temp 是否为空,以避免空指针访问问题。

下面是修正后的代码:

#include <stdlib.h>

typedef struct hash_list_node{
    int score;
    struct hash_list_node* next;
} HashListNode;

HashListNode* List[100];

void initList() {
    for (int i = 0; i < 100; i++) {
        List[i] = NULL; // 将指针数组初始化为 NULL
    }
}

int hashCount(int score)
{
    int hashValue = score % 100;
    int count = 0;
    HashListNode* temp = List[hashValue];
    while (temp != NULL){
        if(temp->score == score){   
            count++;
        }
        temp = temp->next;
    }
    return count;
}

void insertHashNode(int score)
{
    int hashValue = score % 100;
    HashListNode* node = (HashListNode*)malloc(sizeof(HashListNode));
    node->score = score;
    node->next = NULL;
    HashListNode* temp = List[hashValue];
    if (temp == NULL) {
        List[hashValue] = node; // 如果链表为空,将新节点直接插入头部
    } else {
        while (temp->next != NULL){
            temp = temp->next; // 将temp定位到链表末尾
        }
        temp->next = node; // 将新节点连接到末尾
    }
}

修复了上述问题后,应该能够避免段错误的问题。同时,在使用动态内存分配 malloc 后,还需要在合适的时机使用 free 函数进行内存释放,以避免内存泄漏问题。


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^