C程序中的分段故障11错误,我必须计算输入单词的出现次数



我的程序来自K&R在第6.5节中,我们正在研究自指结构。在这里,我们必须计算输入到终端的单词的出现次数。我们必须构建一个单词的二叉树并跟踪计数。我在addtree函数中得到一个分段Fault 11错误。我认为这个函数中的p没有指向正确的内存。但我不确定如何修复它。下面是我的代码:

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#define MAXWORD 100
#define BUFSIZE 100
struct tnode{
char *word;
int count;
struct tnode *left; //left child. referential way of declaring
struct tnode *right;
};
struct tnode *addtree(struct tnode *, char *);
void treeprint(struct tnode *);
int get_word(char *, int);
struct tnode *talloc(void);
char *my_strdup(char *);
int main(){
struct tnode *root;
char word[MAXWORD];
while(get_word(word, MAXWORD) != EOF){
if(isalpha(word[0])){
printf("Still in main going in addtree functionn");
root = addtree(root, word);
}
}
treeprint(root);
return 0;
}
struct tnode *addtree(struct tnode *p, char *w){
int cond;
printf("Inside addtree function.n");
if(p == NULL){ //a new word has arrived
p = talloc();
p->word = my_strdup(w);
p->count = 1;
p->left = p->right = NULL;
}else if((cond = strcmp(p->word, w))==0)
p->count++;
else if(cond < 0)
p->right = addtree(p->right, w);
else
p->left = addtree(p->left, w);
return p;
}
void treeprint(struct tnode *p){
if(p!=NULL){
printf("Coming inside treeprint statement.n");
treeprint(p->left);
printf("%4d    %sn", p->count, p->word);
treeprint(p->right);
}
}
struct tnode *talloc(void){
return (struct tnode *) malloc(sizeof(struct tnode));
}
char *my_strdup(char *w){
char *p;
p = (char *) malloc(strlen(w)+1);
if(p!=NULL)
strcpy(p, w);
return p;
}
char buf[BUFSIZE]; //buffer for ungetch
int bufp = 0; //next free position in buf
int getch(void){
return (bufp>0) ? buf[--bufp] : getchar();
}
void ungetch(int c){
if(bufp >= BUFSIZE)
printf("ungetch: too many characters.n");
else
buf[bufp++] = c;
}
//get next word or character from input
int get_word(char *word, int lim){
int c;
int getch(void);
void ungetch(int);
char *w = word;
while((isspace(c = getch())))
;
if(c != EOF){
*w++ = c;
}
printf("c: %dn", c);
printf("n*w: %c", *w);
if(!isalpha(c)){
*w = '';
return c;
}
for( ; --lim > 0; w++){
if(!isalnum(*w = getch())){
ungetch(*w);
break;
}
}
*w = '';
printf("word[0]: %cn", word[0]);
return word[0];
}

这里崩溃了:

}else if((cond = strcmp(p->word, w))==0)

在第一次运行时,因为root->word从未被分配/初始化。

我强烈建议,在学习C的过程中,也要学习使用C调试器。这里有一个很棒的gdb教程。使用调试器,您几乎可以立即发现类似这样的源问题。

以下是如果您尝试运行此程序,gdb输出的样子,例如:

(gdb) run
Starting program: /home/nick/a.out 
hello darkness my old friend #<-- my keyboard input
c: 104
*w: ?word[0]: h
Still in main going in addtree function
Inside addtree function.
Program received signal SIGBUS, Bus error.
addtree (p=0x23792ac296e9f5c5, w=0x7f7fffff1680 "hello") at test.c:44
44      }else if((cond = strcmp(p->word, w))==0)
Current language:  auto; currently minimal

相关内容

  • 没有找到相关文章

最新更新