cs50 pset5 dictionary.c:这段代码给出了分段错误

时间:2017-08-04 06:05:09

标签: c dictionary trie cs50

我已经为pset5 dictionary.c编写了这段代码。

我在trie数据结构中加载了字典。 它显示了分段错误。

/**
 * Implements a dictionary's functionality.
 */

    #include <stdbool.h>
    #include<stdio.h>
    #include<cs50.h>
    #include<string.h>
    #include "dictionary.h"
    typedef struct node
    {
        char n;
        struct node *next;
    }node;
    int words = 0;
    node *head , *temp;


/**
 * Returns true if word is in dictionary else false.
 */
    bool check(const char *word)
    {
        temp = head;
        int count = 0;
        int l = strlen(word);
        for(int i=0;i<l;i++)
        {
            if(temp[word[i]-'a'].n == word[i])
            {
                temp = temp[word[i] - 'a'].next;
                count++;
            }
            else
                break;
        }
        if(count == l)
        {
            return true;
        }
        return false;
    }


/**
 * Loads dictionary into memory. Returns true if successful else false.
 */


bool load(const char *dictionary)
    {
        int i = 0;
        head = temp = malloc(26*sizeof(node));
        for(i=0;i<26;i++)
        {
            head[i].n = '0';
            head[i].next = NULL;
        }
        FILE *ptr = fopen(dictionary,"r");
        if (ptr == NULL)
        {
            printf("Could not open dictionary"); 
            return false;
        }
        while(feof(ptr))
        {
            char *d= NULL;
            fscanf(ptr,"%s",d);
            words++;
            int l = strlen(d);
            for(int j=0;j<l;j++)
            {
                if(temp[d[j] - 'a'].next == NULL)
                {
                    temp[d[j] - 'a'].n = d[j];
                    temp[d[j] - 'a'].next = malloc(26*sizeof(node));
                    temp = temp[d[j] - 'a'].next;
                    for(int k=0;k<26;k++)
                    {
                        temp[k].n = '0';
                        temp[k].next = NULL;
                    }
                }
                else
                {
                    temp = temp[d[j] - 'a'].next;
                }
            }
            temp = head;
        }
        return true;
    }
    /**
     * Returns number of words in dictionary if loaded else 0 if not yet loaded.
     */
    unsigned int size(void)
    {
        if(words != 0)
        return words;
        return 0;
    }
    /**
     * Unloads dictionary from memory. Returns true if successful else false.
     */
    bool unload(void)
    {
        free(head);
        free(temp);
        return true;
    }

但它显示了分段错误。 我尝试使用我的trie代码,它与其他代码一起工作正常。 输出: -

Segmentation fault

1 个答案:

答案 0 :(得分:0)

您可以从搜索可能访问错误内存位置的位置开始。通过指针搜索访问:是分配的内存和正确初始化的对象?而且指数在范围内? 您可能还有许多其他错误,但这是其中之一:

 char *d= NULL;
 fscanf(ptr,"%s",d);

你需要先在d中分配足够的内存。 并始终确保您的索引<26(如d[j] - 'a'中的temp[d[j] - 'a']

相关问题