【问题标题】:program crashing while assigning a new node to tree node将新节点分配给树节点时程序崩溃
【发布时间】:2016-05-14 09:17:33
【问题描述】:

我为树编写了一个 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) 时出错。我不明白为什么?

【问题讨论】:

  • struct node* temp; --> struct node* temp = malloc(sizeof(*temp));

标签: c pointers memory-management dereference


【解决方案1】:

在你的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;
}

应该完成工作。

【讨论】:

    【解决方案2】:

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

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

    当你完成后,你必须记得再次free内存。

    【讨论】:

      猜你喜欢
      • 2017-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-27
      • 2015-03-22
      • 1970-01-01
      • 2019-08-28
      • 1970-01-01
      相关资源
      最近更新 更多