c - 尝试打印到文件时 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,所以希望你帮我找出我的分段错误并请解释一下。
解决方案
该代码正在打印出二叉树。没有代码显示节点是如何构造的,但在典型的二叉树中,叶节点具有NULL
左右子节点(或者gauche
说droit
是)。
该函数write_to_dot
将在第一个叶节点处失败(如果不是在中间分支节点的空侧),因为racine->gauche
and will racine->droit
be 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 );
}
}
推荐阅读
- highcharts - x 和 y 轴的 Highcharts x-range 图表日期时间类型
- android - 有没有办法以编程方式访问三星的剪贴板内容?
- odoo - 杂货店的 POS/库存
- python - 字符串数据,使用 pyodbc 快速执行时右截断
- ipython - 如何在 IPython Console-Spyder 中查看结果
- sisense - 用 Blox 小部件替换 Sisense 智能标签小部件
- php - 按行号在 DOMDocument 中查找节点
- powershell - Powershell 计算超过 5000 个成员的大型 AD 组的成员
- openlayers - 为什么 WebGLPointsLayer 没有 setStyle
- python - 如何处理 Slurm 中的作业取消?