我有这段代码可以创建一个链接列表,但出现段错误错误。有什么解决办法吗?
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/