gpt4 book ai didi

c - 赛格夫 : invalig write of size 8 when adding a node to the end of a linked list

转载 作者:太空宇宙 更新时间:2023-11-04 05:49:20 24 4
gpt4 key购买 nike

我有这个功能:

int  list_add_elem_at_back(list_t *front_ptr, double elem)
{
list_t item = malloc(sizeof(list_t));
list_t tmp = *front_ptr;

if (item == NULL)
return (0);
item->value = elem;
item->next = NULL;
while (tmp != NULL)
tmp = tmp->next;
tmp->next = item;
return (1);
}

它应该将一个节点添加到以 t_list *front_ptr 开头的列表的后面。

仅供引用:list_tnode_t * 的别名。

执行它时,出现 SegV 崩溃,Valgrind 日志如下:

==3814== Invalid write of size 8
==3814== at 0x4006C1: list_add_elem_at_back (simple_list.c:63)
==3814== by 0x400A83: populate_list (simple_list.c:181)
==3814== by 0x400B5C: main (simple_list.c:202)
==3814== Address 0x521f048 is 0 bytes after a block of size 8 alloc'd
==3814== at 0x4C2FB6B: malloc (vg_replace_malloc.c:299)
==3814== by 0x40067D: list_add_elem_at_back (simple_list.c:56)
==3814== by 0x400A83: populate_list (simple_list.c:181)
==3814== by 0x400B5C: main (simple_list.c:202)
==3814==
==3814== Invalid write of size 8
==3814== at 0x4006EF: list_add_elem_at_back (simple_list.c:66)
==3814== by 0x400A83: populate_list (simple_list.c:181)
==3814== by 0x400B5C: main (simple_list.c:202)
==3814== Address 0x8 is not stack'd, malloc'd or (recently) free'd

第 63 行和第 66 行是 item->next = NULL;tmp->next = item;,这让我觉得它来 self 分配的方式(或者没有?)我对“下一个”节点的内存,但我无法找出问题所在。

感谢任何帮助。

最佳答案

您正在分配 sizeof(list_t),这是一个指针。你必须这样做:

malloc(sizeof(node_t));

正是这个隐藏 * 的糟糕想法的结果。

第二个问题:当headNULL 时,您将向带有&head 的函数传递一个空指针。显然 next 位于偏移量 0x08 处。因为 tmp0,所以 tmp->next 位于 0 + 0x08。可以使用 head = malloc(sizeof(node_t)) 进行快速检查。

关于c - 赛格夫 : invalig write of size 8 when adding a node to the end of a linked list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48104760/

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