Closed. This question is off-topic. It is not currently accepting answers. Learn more
想改进这个问题吗?Update the question所以堆栈溢出的值小于aa>。
三年前关闭。
我在C语言中使用二进制树(LinuxDebian,GCC4.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);
  }
}

最佳答案

分配后不初始化leftright指针,因此它们的值未定义。
使用calloc或手动将指针设置为NULL

关于c - 递归释放二叉树时出现段错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35703449/

10-15 13:56