当我运行以下代码时,它给了我无限循环的结果。但是,如果我注释掉insert
函数ie中的空闲指针行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);
}
当我运行以下代码时,它给了我无限循环的结果。但是,如果我在插入函数ie中注释掉了自由指针行
free(ptr)
,free(ptrnext)
那么它就可以正常工作。
这是未定义的行为。(当您不注释free()
功能时)
释放内存后,必须记住不要再使用它了。
注意:释放后指针可能会或可能不会指向同一块,这是未定义的行为
所以,除非你想不释放指针destroy
或delete
节点。
因此,请勿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
整个列表时调用它
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句