gpt4 book ai didi

c - 双链表问题(核心转储)

转载 作者:行者123 更新时间:2023-11-30 19:48:13 25 4
gpt4 key购买 nike

关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。












想改进这个问题?将问题更新为 on-topic对于堆栈溢出。

8年前关闭。




Improve this question




最近一直在练习数据结构,但遇到一个新问题,当我尝试打印列表时,它提示“core dumped”,我很困惑!

我声明:

struct DOUBLE_LINK_LIST {
char *string;
struct DOUBLE_LINK_LIST *pre;
struct DOUBLE_LINK_LIST *next;
}double_link_list;

链接列表.h:
/* double linked list */
struct DOUBLE_LINK_LIST *init_double_link_list() {
struct DOUBLE_LINK_LIST *new_link = malloc(sizeof(struct DOUBLE_LINK_LIST));
if (new_link==NULL) {
fprintf(stderr, "Insufficient memory!!!");
return NULL;
}
new_link->string = NULL;

return new_link;
}

===============================
这是我得到长度的方法:
int D_get_length(struct DOUBLE_LINK_LIST *link) {
int count;
count = 0;

while (link->next!=NULL) {
count += 1;
link = link->next;
}

return count;
}

int D_create(struct DOUBLE_LINK_LIST *link, char *in) {
if (D_get_length(link)>=STRING_SIZE) {
fprintf(stderr, "Double link list is full!!!");
return ERROR;
}
else {
struct DOUBLE_LINK_LIST *new_node;
new_node = init_double_link_list();
if (new_node==NULL) {
return ERROR;
}
/*new_node->next = link->next;
new_node->pre = link;
link->next = new_node;
if(new_node->next!=NULL) {
new_node->next->pre = new_node;
}
new_node->string = in;*/
new_node->next = link->next;
link->next = new_node;
new_node->string = in;
}

return OK;
}

它确实返回正确的长度,但它不在 create 函数中:
char *D_get_element(struct DOUBLE_LINK_LIST *link, int pos) {
int i;

if (D_is_empty(link)==YES) {
return NULL;
}

printf("_%d_", D_get_length(link));

if (pos <= 0 || pos-1 > D_get_length(link)) {
fprintf(stderr, "Invalid position!!!");
exit(1);
}
else {
for (i = 0; i < pos; ++i) {
link = link->next;
}
}

return link->string;
}

最佳答案

问题是第一个 DOUBLE_LINK_LIST创建,我假设你也使用 init_double_link_list创建第一个。因为你只做malloc这不会清除分配的内存,next 上有一些垃圾指针。

然后我假设您开始将字符串插入其中,因为您的 D_create搬坏了next进入新的,这个坏指针被推到列表的末尾。

然后在某个时候,你会去未知的土地,死得很惨,或者如果你运气不好,它会工作一段时间,然后又死得很惨。

一种解决方案:使用 calloc ,它将用0初始化内存。

其他解决方案:memsetmalloc 之后

更多解决方案:在 null 旁边显式设置

关于c - 双链表问题(核心转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19789807/

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