在递归释放二叉树时获取分段错误

时间:2016-02-29 15:35:47

标签: c

我正在使用C语言中的二叉树(Linux Debian,gcc版本4.9.2),并且在释放malloc分配的内存时遇到了一些麻烦。第一个deltree()工作正常,但第二个deltree()给我一个分段错误。可能是什么原因?

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

/*
  compiling with flags -ansi -Wstrict-prototypes
*/

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

typedef struct treenode node;

void deltree(node *tree);

int main(void){
  node *root;

  printf("First tree\n");
  printf("===================\n");

  root=(node *)malloc(sizeof(node));
  root->data=5;

  root->left=(node *)malloc(sizeof(node));
  root->left->data=4;

  root->right=(node *)malloc(sizeof(node));
  root->right->data=6;

  printf("Root node has data %d\n",root->data);
  printf("Left child has data %d\n",root->left->data);
  printf("Right child has data %d\n",root->right->data);

  deltree(root);  /* NO PROBLEM HERE */

  printf("Second tree\n");
  printf("===================\n");

  root=(node *)malloc(sizeof(node));
  root->data=-7;

  root->left=(node *)malloc(sizeof(node));
  root->left->data=-5;

  root->right=(node *)malloc(sizeof(node));
  root->right->data=-1;

  printf("Root node has data %d\n",root->data);
  printf("Left child has data %d\n",root->left->data);
  printf("Right child has data %d\n",root->right->data);

  deltree(root); /* SEGMENTATION FAULT HERE */

  printf("Finished\n");

  return(EXIT_SUCCESS);
}

void deltree(node *tree){
  if(tree!=NULL){
    deltree(tree->left);
    deltree(tree->right);

    printf(".\n");

    free(tree);
  }
}

1 个答案:

答案 0 :(得分:3)

分配后不会初始化leftright指针,因此它们的值未定义。

使用calloc或手动将指针设置为NULL