【发布时间】:2014-04-27 21:04:50
【问题描述】:
这是课堂作业。我只需要将输入文件中的单词读入树节点,并按频率对它们进行分类。不幸的是,我遇到了段错误。我通过gdb 运行程序,发现故障发生在第二遍 通过addtree 的过程中。它命中strcmp(w, p->word) 并出现故障。
经过进一步调查,这似乎是因为p->word 的值为0x0,就好像该字符串从未被复制到其中一样。我错过了一些非常简单的东西吗?我将尝试在此处仅包含有问题的和相关的代码。 (编辑:看起来除了treeprint之外的一切。)
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#define MAXWORD 100
struct tnode *addtree(struct tnode *, char *);
void treeprint(struct tnode *);
int getword(char *, int);
char *strdup(const char *);
struct tnode
{
char *word;
int count;
struct tnode *left;
struct tnode *right;
};
main()
{
struct tnode *root;
char word[MAXWORD];
root = NULL;
while (getword(word, MAXWORD) != EOF) {
if (isalpha(word[0])) {
root = addtree(root, word);
}
}
treeprint(root);
return 0;
}
int getword(char *word, int lim)
{
char *w = word;
int c;
while (isspace(c = getch())) {}
if (c != EOF)
{
*w++ = c;
}
if (!isalpha(c))
{
*w = '\0';
return c;
}
for ( ; --lim > 0; w++)
{
if (!isalnum(*w = getch()))
{
ungetch(*w);
break;
}
}
*w = '\0';
return word[0];
}
struct tnode *talloc(void)
{
return (struct tnode *) malloc(sizeof(struct tnode));
}
char *strdup(const char *s)
{
char *p;
p = (char *) malloc(strlen(s) + 1);
if (p == NULL)
strcpy(p, s);
return p;
}
struct tnode *addtree(struct tnode *p, char *w)
{
int cond;
if (p == NULL)
{
p = talloc();
p->word = strdup(w);
p->count = 1;
p->left = p->right = NULL;
}
else if ((cond = strcmp(w, p->word)) == 0)
p->count++;
else if (cond < 0)
p->left = addtree(p->left, w);
else
p->right = addtree(p->right, w);
return p;
}
void treeprint(struct tnode *p)
{
if (p != NULL)
{
treeprint(p->left);
printf("%4d %s\n", p->count, p->word);
treeprint(p->right);
}
}
【问题讨论】:
-
结构实例在 C FYI 中不能为空。 Null 仅与指针类型相关。
-
所以你知道,strdup 是 string.h 的一部分,你不必自己写。
-
if (p == NULL) strcpy(p, s);-->>if (p != NULL) strcpy(p, s);(但还有更多错误) -
太棒了。它现在正在运行。如果不是你们,我仍然会因为混淆
=s、==s 和!=s 而在墙上敲打我的头。非常感谢!
标签: c pointers struct segmentation-fault