c - 创建链表时出现段错误

标签 c linked-list segmentation-fault

我有这段代码可以创建一个链接列表,但出现段错误错误。有什么解决办法吗?

    struct node *temp = (struct node*)malloc(sizeof(struct node));
    char *a = title_parser(bytes, temp);
    head = temp;

    temp = (struct node*)malloc(sizeof(struct node));
    title_parser(a, temp);

    puts(a); // Is NULL

    struct node* temp1 = head;
    while(temp1->link != NULL)
    {
            temp1 = temp1->link;
    }
    temp1->link = temp;

编辑:程序遍历函数title_parser后,再次为temp分配内存,但是当第二次调用title_parser时,就会发生段错误。

这是我的 title_parser 代码

char* title_parser(char *bytes, struct node *temp){

char *ptr = strstr(bytes, "<title>");


if (ptr) {

    /* Skip over the found string */
    ptr += 7;
    char *ptr2 = strstr(ptr, "</title>");
    if (ptr2) {
        char* output = malloc(ptr2 - ptr + 1);
        memcpy(output, ptr, ptr2 - ptr);

        output[ptr2 - ptr] = 0;

        if(strcmp(output,"TechCrunch")!=0 && strcmp(output,"VentureBeat")!=0){
            temp->title = output;
            temp->link = NULL;
            puts(temp->title);
            free(output);
            char *load = pubdate_parser(ptr2, temp);
            return load;
        }
        else{
            title_parser(ptr2, temp);
        }
    }
}

}

编辑:另一个问题是,当 title_parser 返回加载时,我在 main 中打印 a 并且输出为 NULL。

最佳答案

在我看来,这个错误不是由malloc线引起的,你可以检查你的函数title_parser(bytes, temp),你可以记下它,然后再次运行你的程序。 这是我的测试代码:

    #include<stdio.h>
    #include<stdlib.h>
    struct node{
        int val;
        struct node *next;
    };

    void main()
    {
       struct node *tmp=(struct node*)malloc(sizeof(struct node));
       tmp->val=1;
       struct node *head=tmp;
       tmp=(struct node*)malloc(sizeof(struct node));
       tmp->val=2;
       printf("%d\n",tmp->val);
    } 

输出是2,所以没有出现预期的segmentfault,你可以尝试一下!

关于c - 创建链表时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30339383/

相关文章:

c - fork与动态库交互

python - C 和 Python 之间的 break 语句有区别吗?

C++如何使用链表添加多项式

java - 需要一个包含 Queue.Node 的封闭实例

代码给我段错误

c - select() 和 poll() 在 Mac OS 上缺少一个封闭的管道

c - 排序和打印数组元素打印出垃圾

ruby - 如何在 Ruby 中创建链表?

c++ - 当我尝试将 char* 分成标记时出现段错误

c++ - 当对象包含指针成员时,堆栈上对象破坏的段错误?