سؤال

This is for a class assignment. I just need to read words from an input file into tree nodes, and catalog them by frequency. Unfortunately, I'm getting a segfault. I've run the program through gdb, and I've found that the fault occurs during the second pass through addtree. It hits strcmp(w, p->word) and faults.

Upon further investigation, it looks like this is because p->word has a value of 0x0, as if the string never got copied into it. Is there something really simple that I'm missing? I'll try to include only the offending and related bits of code here. (edit: looks like that was everything except 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);
    }
}
هل كانت مفيدة؟

المحلول

if (p = NULL)

should be

if (p == NULL)

in strdup

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top