【发布时间】:2019-06-08 18:02:25
【问题描述】:
以下是从文件中读取并将所述文件的每个字符串保存到二叉搜索树的代码。它适用于 1KB 的 txt 文件,但是当尝试使用更大的文件 (2kb) 时,我会遇到分段错误。
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
typedef struct listNode ListNode;
struct listNode {
int id;
ListNode *next;
};
typedef struct treeNode TreeNode;
struct treeNode {
char *word;
char *key;
int freq;
ListNode *head;
TreeNode *left;
TreeNode *right;
};
TreeNode* insertItem(TreeNode *root, char *gword);
void printTreeInorder(TreeNode *v);
void searchforexist(TreeNode *root, char *key);
#define MAX 25
int main()
{
char word[MAX];
TreeNode *root = NULL;
FILE *fp=fopen("input.txt","r");
if (fp!=NULL)
{
while (fscanf(fp,"%s \n",word) != EOF)
{
root = insertItem(root,word);
if (strcmp(word, "eof")==0)
break;
}
}
fclose(fp);
printTreeInorder(root);
printf("\n");
return 0;
}
TreeNode* insertItem(TreeNode *root, char *gword)
{
TreeNode *v = root;
TreeNode *pv = NULL;
while (v != NULL)
{
pv = v;
int comp = strcmp(gword, v->word);
if (comp < 0) v=v->left;
else if (comp > 0) v=v->right;
else
{
char *key=v->word;
searchforexist(root,key);
return root;
}
}
TreeNode *tmp = (TreeNode *) malloc(sizeof(TreeNode));
tmp->word=strdup(gword);
tmp->left=tmp->right=NULL;
tmp->freq=1;
if (root != NULL)
{
if (strcmp(gword, pv->word) < 0) pv->left=tmp;
else pv->right=tmp;
} else root=tmp;
return root;
}
void searchforexist(TreeNode *root, char *key)
{
if (root == NULL || root->key == key)
root->freq ++;
if (root->key < key)
searchforexist(root->right, key);
searchforexist(root->left, key);
}
void printTreeInorder(TreeNode *v)
{
if (v==NULL) return;
printf("(");
printTreeInorder(v->left);
printf(")");
printf(" %.4s ", v->word);
printf("(");
printTreeInorder(v->right);
printf(")");
}
按预期运行的 Txt 文件: { 单词在此测试文件中用于测试目的 将字符串转换为数据结构。 }
但是,如果我将其更改为此,则会出现分段错误: { 单词在此测试文件中用于测试目的 将字符串转换为数据结构。 & 单词在此测试文件中用于测试目的 将字符串转换为数据结构。 }
【问题讨论】:
-
除了你在这里展示的内容之外,还有很多很多的机会可以让你的英雄计划绊倒。请发minimal reproducible example。
-
scanf格式的尾随空格通常是个坏主意,因为这意味着函数必须读取直到遇到非空格字符。 -
fscanf(fp,"%s \n",word) != EOF如果文本的任何一行大于MAX,则可以写越界,请使用fgets。 -
还要注意
fclose调用的位置。目前可以用空指针调用。 -
请注意:我收到编译器警告C4717: 'searchforexist': recursive on all control paths, function will cause runtime stack overflow
标签: c file segmentation-fault fopen