Ошибка Сегментации 11 в программе C, где я должен был бы посчитать вхождения введенных слов - PullRequest
0 голосов
/ 28 апреля 2020

Моя программа взята из книги по языку программирования C от K & R в разделе 6.5, где мы исследуем самоссылочные структуры. Здесь мы должны были бы посчитать количество вхождений слов, введенных в терминал. Мы должны были бы построить двоичное дерево слов и отслеживать количество. Я получаю ошибку ошибки сегментации 11 в функции addtree. Я думаю, что р в этой функции не указывает на правильную память. Но я не уверен, как это исправить. Вот мой код ниже:

#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 function\n");
            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    %s\n", 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: %d\n", c);
    printf("\n*w: %c", *w);
    if(!isalpha(c)){
        *w = '\0';
        return c;
    }
    for( ; --lim > 0; w++){
        if(!isalnum(*w = getch())){
            ungetch(*w);
            break;
        }
    }
    *w = '\0';
    printf("word[0]: %c\n", word[0]);
    return word[0];
}


1 Ответ

0 голосов
/ 28 апреля 2020

Здесь происходит сбой:

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

при первом запуске, потому что root -> слово никогда не выделялось / не инициализировалось.

Я бы настоятельно рекомендовал, так как вы работаете на своем пути Изучив 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
...