首页 > 解决方案 > C中字母链表中的分段错误

问题描述

我的字母链表中出现分段错误,我将其固定到最后一个 else 语句中的 prev。

else 
{
    prev->next = new_node;
    new_node->next = ptr;
    return 0;
}

我该如何解决这个问题?

int add(char *str, char *file) {
struct word_node *new_node = malloc(sizeof(struct word_node));

unsigned len = strlen(str) + 1;
char *s = malloc(len);
memcpy(s, str, len);

new_node->data = s;
new_node->count = 1;
new_node->filename = file;
new_node->next = NULL;

// struct word_node 

if (head == NULL)
{
    head = new_node;
    return 0;
}

struct word_node* ptr = head;
struct word_node* prev = NULL;

while (ptr != NULL)
{
    if (strcmp(ptr->data, new_node->data) > 0)
    {
        break;
    }
    ptr = ptr->next;
}

if (ptr == head)
{
    new_node->next = head;
    head = new_node;
    return 0;
}
else 
{
    prev->next = new_node;
    new_node->next = ptr;
    return 0;
}
}

标签: cstructlinked-listsingly-linked-listfunction-definition

解决方案


您的代码简化为:

struct word_node* prev = NULL;

prev->next = new_node;

现在看到问题了吗?

要运行第二行,您必须prev在使用之前将其初始化为有效的值。


推荐阅读