程序崩溃时,将新节点分配给树节点

问题描述:

我已经编写了一个用于树的c程序。程序崩溃时,将新节点分配给树节点

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

struct node{ 
    int data; 
    struct node *left; 
    struct node *right; 
}; 

struct node* newNode(int value){ 
    struct node* temp; 
    temp->left = NULL; 
    temp->right = NULL; 
    temp->data = value; 

    return temp; 
} 

int main(){ 
    struct node *root; 
    root = newNode(60); 
    root->left = newNode(40); 
    root->right = newNode(80); 
    root->left->left = newNode(30); // program crashes here. 
    root->left->right = newNode(50); 

} 

这是我写的另一个程序的子部分。在调试时,我意识到我在分配newNode(30)时遇到错误。我不明白为什么?

+1

'struct node * temp;' - >'struct node * temp = malloc(sizeof(* temp));'' – BLUEPIXY

在你newNode()功能,你正在做

struct node* temp; 
temp->left = NULL;  //invalid memory access 
temp->right = NULL; //invalid memory access 
temp->data = value; //invalid memory access 

但是,temp没有分配任何有效的内存。当您取消引用无效指针时,它会调用undefined behavior

在解除引用temp之前,您需要将内存分配给temp。您可以使用malloc()和家庭得到这个工作,像,

struct node* temp = malloc (sizeof *temp); 
if (temp) 
{ 
    temp->left = NULL; 
    temp->right = NULL; 
    temp->data = value; 
} 

应该把工作做好。

您需要为新节点分配内存。像

struct node* temp; 
temp = malloc(sizeof(struct node)); 

当你做了你一定要记得再次free内存。