【问题标题】:Segmentation fault on a null struct?空结构上的分段错误?
【发布时间】: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


【解决方案1】:
if (p = NULL)

应该是

if (p == NULL)

strdup

【讨论】:

  • 看起来 ouah 的帖子在我评论的时候消失了……冒着让自己尴尬的风险,初始化是否完全有必要?当我看它时,对我来说这似乎是完全合乎逻辑的。将其设置为NULL,然后调用addtree。如果是NULL,请为其分配适当的内存。我还在strdup 中更正了这个问题,它运行了,但它只打印出一个(谢天谢地是有限的)系列1。没有添加任何单词,也没有频率超过1。有什么见解吗?我附上上面的treeprint函数供参考。
猜你喜欢
  • 2021-06-12
  • 2014-08-12
  • 2011-08-24
  • 2020-02-17
  • 2014-01-18
  • 2023-04-04
  • 2018-11-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多