有人会在我的代码中识别可能导致段错误的内容吗?

时间:2015-11-03 09:03:30

标签: c trie cs50

这是我的CS50任务。我必须制作一个拼写检查器,将字典加载到数据结构中。在文件大小增加之前,段错误不会发生。

:(a+b)

将字典加载到内存中。

//Trie structure
typedef struct node {

    bool is_word;
    struct node* children[27];
}node;

node* root;

// maximum length for a word
#define LENGTH 45
//global counter for total words in dic
int SIZE = 0;

1 个答案:

答案 0 :(得分:0)

我不确定这是否是主要问题,但这部分代码缺乏健壮性:

        int letter_pos = tolower(word[i]) - 'a';

如果letter_pos此时无效(例如因为word[i]不是字母),那么所有后续操作都会产生UB。

我至少会在这里添加一个assert

        int letter_pos = tolower(word[i]) - 'a';
        assert(letter_pos >= 0 && letter_pos < sizeof(nav->children) / sizeof(nav->children[0]));

由于您的数组大小为27,我猜您想将最后一个元素用于非字母字符,因此您可能希望使代码更像这样:

        int letter_pos;
        if (isalpha(word[i]))                    // if 'A'..'Z' or 'a'..'z'
            letter_pos = tolower(word[i]) - 'a'; // index = 0..25
        else
            letter_pos = 'z' - 'a' + 1;          // index = 26
        assert(letter_pos >= 0 && letter_pos < sizeof(nav->children) / sizeof(nav->children[0]));
相关问题