首页 > 解决方案 > 尝试打印到文件时 C 中的分段错误错误

问题描述

我创建了一个函数,它应该在参数中获取二叉树,在用户输入中获取文件名,并在该文件中打印二叉树,以便稍后通过 graphviz 转换为图片。

提供的二叉树类型是:

struct noeud_s;

typedef struct noeud_s noeud;

typedef noeud* arbre;

struct noeud_s{
  char* valeur;
  arbre gauche;
  arbre droit;
};

我创建的 2 个函数是:

void create_dot(arbre racine)
{
  FILE *f;
  char file_name[100];
  printf ("Nom du fichier a creer (Ajouter .dot a la fin): ");
  scanf ("%s", file_name);
  printf("Name: %s\n", file_name);
  printf ("Creation du fichier dot\n");
  f = fopen(file_name, "w");
  if (f == NULL)
  {
    printf("NULL\n");
  }
  fprintf(f, "digigraph tree {\n");
  write_to_dot(f, racine);
  fprintf(f, "}");
  fclose(f);
}

void write_to_dot(FILE *f, arbre racine)
{
  if (racine == NULL)
  {
    return;
  }
  if (racine != NULL)
  {
    fprintf(f, "%s -> %s [label = \"non\"]\n", racine -> valeur, racine -> gauche -> valeur);
    fprintf(f, "%s -> %s [label = \"oui\"]\n", racine -> valeur, racine -> droit -> valeur);
    write_to_dot(f, racine -> gauche);
    write_to_dot(f, racine -> droit);
  }
  return;
}

就调试而言,我已经推断出我的分段错误发生在 write_to_dot 函数内部。但是因为我不能正确处理gdb,所以希望你帮我找出我的分段错误并请解释一下。

标签: csegmentation-faultbinary-tree

解决方案


该代码正在打印出二叉树。没有代码显示节点是如何构造的,但在典型的二叉树中,叶节点具有NULL左右子节点(或者gauchedroit是)。

该函数write_to_dot将在第一个叶节点处失败(如果不是在中间分支节点的空侧),因为racine->gaucheand will racine->droitbe NULL,但它们仍然被取消引用 -racine->gauche->valeur没有任何检查。

虽然我没有所有代码,但至少测试这种情况将解决其中一个问题:

void write_to_dot ( FILE *f, arbre racine )
{
    if ( racine != NULL )
    {
        if (racine->gauche != NULL)
            fprintf ( f, "%s -> %s [label = \"non\"]\n", racine->valeur, racine->gauche->valeur );
        else
            fprintf ( f, "%s -> NULL [label = \"non\"]\n", racine->valeur );

        if (racine->droit != NULL)
            fprintf ( f, "%s -> %s [label = \"oui\"]\n", racine->valeur, racine->droit->valeur );
        else
            fprintf ( f, "%s -> NULL [label = \"oui\"]\n", racine->valeur );

        write_to_dot ( f, racine->gauche );
        write_to_dot ( f, racine->droit );
    }
}

推荐阅读