gpt4 book ai didi

c - 为什么使用 free() 会导致无限循环

转载 作者:行者123 更新时间:2023-11-30 15:07:25 24 4
gpt4 key购买 nike

当我运行以下代码时,它给出了无限循环结果。但是,如果我注释掉 insert 函数中的自由指针行,即 free(ptr)free(ptrnext) 那么它就可以正常工作。谁能解释一下为什么会这样?

我非常确定 print 和 takeInput 工作正常,因此可以忽略。

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

typedef struct Nodes{
struct Nodes * next;
int val;
}Node;

//Function to create a linked list
Node * takeInput(){
int data;
Node *start =NULL ;
Node *tail=NULL;

printf("Enter the number of nodes");
int num,i;
scanf("%d",&num);
for(i=1;i<=num;i++){
if(start==NULL){
start=malloc(sizeof(Node));
puts("Enter data");
scanf("%d",&data);
start->val=data;
start->next=NULL;
tail=start;
}
else{
Node * ptr = malloc(sizeof(Node));
puts("Enter data" );
scanf("%d",&data);
ptr->val=data;
tail->next=ptr;
tail=tail->next;
}

}
tail->next=NULL;
return start;
}

//Function to print
void print(Node * head){
Node*ptr=head;
while(ptr!=NULL){
printf("%d->",ptr->val);
ptr=ptr->next;
}
}

//Function to insert a node in given linked list
Node * insert(Node *start){
int i,data;

puts("Enter pos");
scanf("%d",&i);

puts("Enter data");
scanf("%d",&data);

Node * ptr=malloc(sizeof(Node));
ptr->val=data;
ptr->next=NULL;

if(i==1){

ptr->next=start;
start=ptr;

free(ptr);

}
else{
Node * ptrnext=start;
while(i!=1){
ptrnext=ptrnext->next;
i--;
}

ptr->next=ptrnext->next;
ptrnext->next=ptr;

free(ptr);
free(ptrnext);

}
return start;
}

int main(void){
Node * start =takeInput();
start=insert(start);
print(start);
}

最佳答案

When I run the following code, it gives me an infinite looping result. However if I comment out the free pointer lines in the insert function i.e. free(ptr) and free(ptrnext) then it works fine.

  • 这是未定义的行为(当您不注释 free() 函数时)

  • 释放内存后,您必须记住不要再使用它。

Note : the pointer might or might not point the same block after freeing, it's undefined behavior

  • 所以不要释放指针,除非你想destroydelete节点。

  • 所以不要使用 free()insert功能就像您没有删除任何节点一样。

<小时/>
  • 除此之外,我没有看到任何在程序结束时释放内存的函数。

  • 始终确保在最后使用delete()释放已分配的内存功能。

  • 这是 delete 的典型实现功能

    void delete(Node* start)
    {
    Node* temporary = NULL;
    while(start != NULL)
    {
    temporary = start->next; //saving next node address
    free(start); //freeing current node
    start = temporary; //assigning start with next node address
    }

    printf("successfully destroyed the list!"); //function exit message
    }
  • main() 末尾调用它功能或当您希望 delete整个列表

关于c - 为什么使用 free() 会导致无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38281141/

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