gpt4 book ai didi

c - "Pointer being freed not allocated error"

转载 作者:行者123 更新时间:2023-11-30 20:36:37 25 4
gpt4 key购买 nike

我正在尝试运行一个删除链表第 n 个元素的函数(使用从零开始的索引)。即使我不必 malloc 任何东西,我也会收到此错误:“ev(10676,0x7fff73f9d300) malloc: * error for object 0x7fddc2404c10: point being freed was not allocate*在malloc_error_break中设置断点进行调试”

这是代码:

typedef struct intlist intlist;

struct intlist {
int val;
intlist* next;


intlist* intlist_remove_nth(intlist *xs, unsigned int n)
{
int i = 0;
if (n == 1)
{
intlist *tempremovefirst = xs->next;
free(xs);
return tempremovefirst;
}
intlist *temp = xs;
for (temp = xs; i != n - 1; i++)
{
temp = temp->next;
}
intlist *temp2 = temp->next;
temp->next = temp->next->next;

free(temp2);
return xs;
}

void evidence_intlist_remove_nth()
{
intlist *il1 = intlist_cons(1, NULL);
intlist *il2 = intlist_cons(4, il1);
intlist *il3 = intlist_cons(6, il2);
intlist *il4 = intlist_cons(8, il3);
intlist *il5 = intlist_cons(19, il4);
intlist *il6 = intlist_cons(24, il5);
intlist *il7 = intlist_cons(101, il6);
printf("expecting 101 24 19 6 4 1: ");
intlist_print(intlist_remove_nth(il7, 4));
printf("\n");
free(il1);
free(il2);
free(il3);
free(il4);
free(il5);
free(il6);
free(il7);
}

int main(int argc, char *argv[])
{
evidence_intlist_remove_nth();
return 0;
}

最佳答案

如果您没有分配列表中的项目,则不应释放它们。 free() 仅用于释放由 malloc() 或其亲属之一返回的内存。

关于c - "Pointer being freed not allocated error",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35530791/

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