Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/60.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C语言中使用free()函数_C_Linked List_Malloc_Free - Fatal编程技术网

在C语言中使用free()函数

在C语言中使用free()函数,c,linked-list,malloc,free,C,Linked List,Malloc,Free,我编写了一个函数,使用malloc在链表的末尾添加动态创建的节点。然后在函数的最后一行,我尝试释放指针temp的内存空间 addnodelast(int data){ struct node* temp =(struct node*)malloc(sizeof(struct node)); temp->data=data; temp->link=NULL; struct node*p=head; while(p->link!=NULL) { p=p->link;

我编写了一个函数,使用malloc在链表的末尾添加动态创建的节点。然后在函数的最后一行,我尝试释放指针temp的内存空间

addnodelast(int data){
struct node* temp =(struct node*)malloc(sizeof(struct node));
temp->data=data;
temp->link=NULL;
struct node*p=head;
while(p->link!=NULL)
{
    p=p->link;
}
p->link=temp;
free(temp);
}


但是在执行时,我无法打印列表,因为它无限打印随机值。但是当我删除/注释最后一行freetemp时,它工作正常。

您为新节点分配了空间并将其添加到列表中;temp指向此节点。当您调用freetemp时,您并没有释放temp占用的空间,而是释放它指向的:您刚刚添加到列表中的节点。

在p->link=temp之后,temp变量的值也存在于p->link中

如果该地址被释放,那么p->link将引用释放的内存,这些内存将被重新用于其他目的,从而损坏数据

我无法打印列表,因为它是无限随机打印的 但是当我删除/注释最后一行freetemp时,它就可以工作了 都很好

这并不奇怪。当您释放添加到列表中的节点,然后尝试打印/访问它时,您正在调用该节点,因为就您的程序而言,已取消分配内存的节点不再存在。因此,您可以将这些节点都变成


因此,在您不再需要访问列表之前,您不应该释放节点。

我在这段代码中没有看到任何打印。此外,我看不到任何有意义的东西。释放刚刚添加的节点是一个逻辑错误。您过早地调用free。是的,在使用freetmp之后,temp不会指向新创建的节点。但这不会影响列表,因为我已经存储了节点的地址->link=temp。那么为什么我的打印功能不能使用free?你认为free有什么作用?@KrishnaBagaria,因为内存在释放后不再属于你。它可以被另一个进程覆盖。@ScottHunter假设temp变量的地址是100,其内容是200,这是新创建的节点的地址。所以freetemp会擦除内存位置200,而不是100?@KrishnaBagaria:free不会擦除任何内容;它释放内存,以便在其他地方使用和修改。但您是正确的,因为它不会更改包含被释放地址的变量。