gpt4 book ai didi

c - 链表插入导致 sysmalloc 断言错误

转载 作者:行者123 更新时间:2023-11-30 15:59:19 28 4
gpt4 key购买 nike

我编写了一个代码来将新成员添加到列表中。当我添加两个成员时它工作正常。但是,一旦我添加第三个并编译并运行代码,就会出现错误。代码及错误如下:

#include<stdio.h>
#include<stdlib.h>

struct list_no {
struct list_no *prev,*nest;
struct linked_list *fnl;
int seq_no;
};
static int counter = 0;

struct list_no *lists,*first;

int add_list()
{
struct list_no *temp;

counter++;
if(lists == '\0')
{
lists = (struct list_no *)malloc(sizeof(struct list_no));
lists->prev = '\0';
lists->nest = '\0';
lists->fnl = '\0';
lists->seq_no = 1;
first = lists;
}
else
{
temp = lists;
lists->nest = (struct list_no *)malloc(sizeof(struct linked_list));
lists = lists->nest;
lists->fnl = '\0';
lists->prev = temp;
lists->nest = NULL;
lists->seq_no = counter;
}
return 0;
}

int main()
{
int i=0,lcount;
int i=0,lcount;

char ch = 'y';
first = '\0';
lists = first;
int w;

while(i != 3)
{
add_list();
printf("\n the val ::%d\n",lists->seq_no);
i++;
}

return 0;
}

./a.out 之后出现的错误消息是:

the val ::1
the val ::2

a.out: malloc.c:3097: sYSMALLOc: Assertion `(old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 * (sizeof(size_t))) - 1)) & ~((2 * (sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long)old_end & pagemask) == 0)' failed.
Aborted

为什么无法添加第三个成员?

最佳答案

您的第二个 malloc 使用 sizeof(struct linked_list),应为 sizeof(struct linked_no)
我猜这个结构比 list_no 小,所以在写入时会损坏内存。
在第三次分配时,malloc 发现损坏并感到不安。

其他一些要点:

  1. “next”应拼写为“x”,而不是“nest”。
  2. 指针应该用NULL初始化,而不是'\0'(最终结果相同,但NULL是正确的类型)。
  3. 您应该尝试消除条目分配和初始化的重复(第一次和后续时间)。您的主要错误部分是由于这种重复造成的。

关于c - 链表插入导致 sysmalloc 断言错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9061267/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com