C语言 分割错误:我的动态链表为 11



data.h

struct Sub {
int n;
struct Sub *next;
}
struct Super {
struct Sub *Sub
void (*addSub)(struct Super *self, struct Sub *subRef);
}

数据.c

static void addSub(struct Super *self, struct Sub *subRef) {
struct Sub *head = self->Sub;
while(head != NULL) { // throwing segmentation fault somewhere here
head = head->next;
}
// assign subRef once we reach to the end.
}
struct Super *newSuper() {
struct Super *super = malloc(sizeof(struct Super));
super->addSub = addSub;
return super;
}

data_test.c

int main() {
struct Super *super = newSuper();
super->addSub(super, malloc(sizeof(struct Sub)));
return 0;
}

我对 C 比较陌生,很久以前就实现了链表,但似乎无法解决空问题,这就是过去的情况。如何检测列表的末尾并将新值添加到末尾?

你必须初始化你的新对象

struct Super *newSuper() {
struct Super *super = malloc(sizeof(struct Super));
super->addSub = addSub;
super->Sub = NULL;
return super;
}

恶意的内存不会清除为任何值;它包含垃圾。

您还应该有一个 newSub 函数来创建 Sub 对象的实例,而不是使用原始 malloc 的调用方

你的addSub函数没有做真正的事情,意味着它没有添加任何东西。 您正在遍历列表的null节点并丢失父节点。最好检查head->next != null,然后将sub添加到末尾,如下所示。(我假设您想将subRef添加到列表的末尾)

static void addSub(struct Super *self, struct Sub *subRef) {
struct Sub *head = self->Sub;
if(head == NULL)
{
self->Sub = sub;
return;
}
while(head->next != NULL) { // throwing segmentation fault somewhere here
head = head->next;

head->next = subRef;
subRef->next = NULL; //This step is only required if subRef->next 
//was not set to null before the call
}

最新更新