0

Just got my speller working. Except for the unload func. I feel that idea is right, but maybe the implementation is wrong. Words are not that long, so i figured that recursive solution wouldn't result in stack overflow, but it seems that it is, cause i get Segfault on this code. node* first is global.

bool load(const char *dictionary) {
    FILE *fp = fopen(dictionary, "r");
    if (fp == NULL) {
        printf("Could not open %s.\n", dictionary);
        fclose(fp);
        return false;
    }
    //initialize the first (pointer) node(which cannot be a word itself)
    first=malloc(sizeof(node));
    if (first==NULL) return false;
    for (int i = 0; i<27;i++) {
        first->keys[i]=NULL;
    }
    first->isWord=false;
    node* thisNode=first;
    for (int c = fgetc(fp); c != EOF; c = fgetc(fp)) {
        if (c != '\n') {
            //map chars to {0...26}
            if (c>96) c-=97;
            else if (c==39) c=26;
            else c-=65;
            //allocates memory for a new node in an 
            //appropriate place (depending on what char it is)
            if (!thisNode->keys[c]) thisNode->keys[c]=malloc(sizeof(node));
            //next node is set as current
            thisNode=thisNode->keys[c];
        } else {
            // we must have found a whole word
            //so bool is true
            thisNode->isWord=true;
            //reseting the whole thing in order to 
            //correctly process the next word
            thisNode=first;
            sizer++;
        }
    }
    return true;
}

/**
 * Returns number of words in dictionary if loaded else 0 if not yet loaded.
 */
unsigned int size(void) {
    return sizer;
}

/**
 * Unloads dictionary from memory. Returns true if successful else false.
 */
bool realunload (node* current) {
    for (int c=0; c<27;c++) {
        if(current->keys[c]!=NULL) realunload (first->keys[c]);
    }
    free(current);
    return true;
}

bool unload(void) {
    for (int c=0; c<27;c++) {
        if(first->keys[c]!=NULL) realunload (first->keys[c]);
    }
    free(first);
    return true;
}

1 Answer 1

0

Found my error. Realunload was passing not current but the first node recursively.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .