[英]Why does my program crashes when I tried adding a node inside a function but works in the main function
I tried allocating a new node for a linked list using: 我尝试使用以下方法为链表分配新节点:
struct node *n;
n=(struct node*)malloc(sizeof(struct node));
When I try to do this inside a function which I call newnode()
, it crashes. 当我尝试在我称为newnode()
的函数中执行此操作时,它崩溃了。 However, when it works when it is done inside the main()
function.My full code is as follows: 但是,当它在main()
函数内部完成时,我的完整代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
struct node{
int item;
struct node *next;
};
struct linkedlist{
int size;
struct node *head;
};
void split(struct linkedlist *LL,struct linkedlist *L_odd,
struct linkedlist *L_even);
void printlist(struct linkedlist *LL);
void generate();
void newnode(int i,struct linkedlist *LL);
int main(){
struct linkedlist *L=(struct linkedlist*)malloc(sizeof(struct linkedlist));
L->head->item=1;
newnode(2,L);
newnode(3,L);
printlist(L);
return 0;
}
void split(struct linkedlist *LL,struct linkedlist *L_odd,
struct linkedlist *L_even){
bool odd=1;
bool start=1;
struct node *temp=malloc(sizeof(struct node));
struct node *tempo=L_odd->head;
struct node *tempe=L_even->head;
temp=LL->head;
while (temp->next != NULL){
if(odd==1){
if (start == 1 ){
start=0;
}
else{
tempe->next=temp->next;
tempe=tempo->next;
}
tempo->item=temp->item;
odd=0;
}
else if(odd==0){
tempo->next=temp->next;
tempo=tempo->next;
L_even->head->item=temp->item;
odd=1;
}
temp=temp->next;
}
}
void printlist(struct linkedlist *LL){
struct node *temp=LL->head;
do{
printf("%d ",temp->item);
temp=temp->next;
}while(temp!= NULL);
}
void generate(){
}
void newnode(int i,struct linkedlist *LL){
struct node *n;
n=(struct node*)malloc(sizeof(struct node)); //Program crashes here
printf("%d",LL->head->item);
//n->item=i;
struct node *temp=LL->head;
while (temp->next!=NULL){
temp=temp->next;
}
//temp->next=n;
//n->next=NULL;
}
Why is this so? 为什么会这样呢?
In your main()
function, 在您的main()
函数中,
L->head->item=1;
L->head
is uninitialized. L->head
未初始化。 By de-referencing, you're invoking undefined behavior . 通过取消引用,您正在调用未定义的行为 。
You need to allocate memory to L->head
before you de-reference that pointer. 在取消引用该指针之前,需要将内存分配给L->head
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.