Question

In: Computer Science

Please provide assistance to fix the segmentation fault error I am receiving and solve the following...

Please provide assistance to fix the segmentation fault error I am receiving and solve the following problem I am working on:

My goal is to build a Trie data structure in C++ that can do the following:

- Capable to insert any given dictionary .txt file filled with a single word per line (i.e. file includes ant, bat, car, desk, etc.) into the Trie. A sample dictionary file that I'm working with can be found at http://txt.do/1pht5

- Prompts the user to input some prefix search and provides an autocomplete suggestion (i.e. file includes bat, bar, bass, and user inputs ba which should suggest bat, bar, bass, etc.)

- Lastly, if the user inputs a prefix search that is not within the Trie, it will recommend the top 3 most similar entries in the Trie (i.e. user prefix input is baq which is not part of the dictionary txt file but bat, bar, bass are which should be suggested)

I have been able to write the following code so far but I'm having difficulties in fixing the segmentation error and making it run.

#include<bits/stdc++.h>
#define alphabet_size 26
using namespace std;

class TrieNode {
    public:
    TrieNode* children[alphabet_size];
    bool endofLeaf;
    
    TrieNode(){
        for(int i = 0; i < alphabet_size; i++)
            children[i] = NULL;
            endofLeaf = false;
    }        
};

class Trie {        
    public:
        TrieNode* root;
        Trie() {root = new TrieNode();}      
        void Dict_insert(string word){
            TrieNode* temp = root;
            for(int i = 0; i < word.length(); i++){
                if(temp->children[word[i]-'a'] == NULL){
                    temp->children[word[i]-'a'] = new TrieNode(); 
                }
                temp = temp->children[word[i]-'a'];        
            }
            temp->endofLeaf = true;
        }

        bool search (string word){
            TrieNode* tmp = root;
            for(int i = 0; i < word.size(); i++)
            {
                if(tmp->children[word[i]-'a'] == NULL){
                    return false;
                }
                tmp = tmp->children[word[i]-'a'];
            }
            return tmp;
        }

        void auto_recommendation(string word){
            TrieNode* autorec = root;
            if(autorec->endofLeaf == true)
                cout << word << endl;
            for(int i = 0; i < alphabet_size; i++){
                if(autorec->children[i] != NULL){ 
                    word.push_back((char)i); 
                    auto_recommendation(word); 
                    word.pop_back(); 
                }
            }
        }
};

int main(){
    Trie* t = new Trie();    
    fstream dictionaryfile;
    dictionaryfile.open("Dictionary.txt",ios::in);  
    if (dictionaryfile.is_open()){ 
        string DictEntry;
        while(getline(dictionaryfile, DictEntry)){ 
            t->Dict_insert(DictEntry);
        }
    dictionaryfile.close(); 
    } 
    string searchQuery;
    cout << "Type in a search: " << endl;
    getline(cin,searchQuery); 
    cout << "/nDid you mean: \n" << endl;
    t->search(searchQuery);
    if (t->search(searchQuery) == false)
        /* Call a recommendation search function which recommends the top 3 most similar entries within the Trie*/
        cout<<"Did you mean:\n";
        //cout top 3 most similar entries within the Trie
    else
        t->auto_recommendation(searchQuery);
    return 0;
}

Solutions

Expert Solution

Hi,

You are getting seg fault because you are not using alid null-terminated C-style string.

dictionaryfile.open("Dictionary.txt\n",ios::in); // use \n you will not get seg fault

I am attaching code for reference and my compiled code and runnig code.

#include<bits/stdc++.h>
#define alphabet_size 26
using namespace std;

class TrieNode {
        public:
                TrieNode* children[alphabet_size];
                bool endofLeaf;

                TrieNode(){
                        for(int i = 0; i < alphabet_size; i++)
                                children[i] = NULL;
                        endofLeaf = false;
                }
};

class Trie {
        public:
                TrieNode* root;
                Trie() {root = new TrieNode();}
                void Dict_insert(string word){
                        TrieNode* temp = root;
                        for(int i = 0; i < word.length(); i++){
                                if(temp->children[word[i]-'a'] == NULL){
                                        temp->children[word[i]-'a'] = new TrieNode();
                                }
                                temp = temp->children[word[i]-'a'];
                        }
                        temp->endofLeaf = true;
                }

                bool search (string word){
                        TrieNode* tmp = root;
                        for(int i = 0; i < word.size(); i++)
                        {
                                if(tmp->children[word[i]-'a'] == NULL){
                                        return false;
                                }
                                tmp = tmp->children[word[i]-'a'];
                        }
                        return tmp;
                }

                void auto_recommendation(string word){
                        TrieNode* autorec = root;
                        if(autorec->endofLeaf == true)
                                cout << word << endl;
                        for(int i = 0; i < alphabet_size; i++){
                                if(autorec->children[i] != NULL){
                                        word.push_back((char)i);
                                        auto_recommendation(word);
                                        word.pop_back();
                                }
                        }
                }
};

int main(){
        Trie* t = new Trie();
        ifstream dictionaryfile;
        dictionaryfile.open("Dictionary.txt\n",ios::iun);
        if (dictionaryfile.is_open()){
                string DictEntry;
                while(getline(dictionaryfile, DictEntry)){
                        t->Dict_insert(DictEntry);
                }
                dictionaryfile.close();
        }
        string searchQuery;
        cout << "Type in a search: " << endl;
        getline(cin,searchQuery);
        cout << "/nDid you mean: \n" << endl;
        t->search(searchQuery);
        if (t->search(searchQuery) == false)
                /* Call a recommendation search function which recommends the top 3 most similar entries within the Trie*/
                cout<<"Did you mean:\n";
        //cout top 3 most similar entries within the Trie
        //    else
        //            t->auto_recommendation(searchQuery);
        //                return 0;
                        }


Related Solutions

I am creating SAS code, but am receiving an errors " ERROR: Value is out of...
I am creating SAS code, but am receiving an errors " ERROR: Value is out of range or inappropriate. ERROR: No body file. HTML5(WEB) output will not be created." This is the code: option ls=65 ps=65; data one; input IQ; cards; 145 139 122 ; title 'Normal Quantile - Quantile Plot for IQ'; ods graphics on; proc univariate data=one; qqplot IQ / normal (mu=est sigma=est); run;
I am getting an error at linen 57 and can't figure out how to fix it....
I am getting an error at linen 57 and can't figure out how to fix it. // Java program to read a CSV file and display the min, max, and average of numbers in it. import java.io.File; import java.io.FileNotFoundException; import java.util.Arrays; import java.util.Scanner; public class Main {     // method to determine and return the minimum number from the array     public static int minimum(int numbers[])     {         int minIdx = 0;         for(int i=1;i<numbers.length;i++)         {             if((minIdx...
C++ Bank Account Error Fix, full code. I am using Dev-C++ to Compile and Execute. The...
C++ Bank Account Error Fix, full code. I am using Dev-C++ to Compile and Execute. The project is below, I have supplied the code and I'm getting an error in SavingsAccount.h file. 17   5   C:\Users\adam.brunell\Documents\Classes\C++\Week4\SavingsAccount.h   [Error] 'SavingsAccount::SavingsAccount(std::string, double, double)' is protected A.Assume i.SavingsAccount: Assume an Interest Rate of 0.03 ii.HighInterestSavings: Assume an Interest Rate of 0.05, Minimum Balance = $2500 iii.NoServiceChargeChecking: Assume an Interest Rate = 0.02, Minimum of Balance = $1000 iv.ServiceChargeChecking – Assume account service charge = $10,...
please correct the error and fix this code: (i need this work and present 3 graphs):...
please correct the error and fix this code: (i need this work and present 3 graphs): Sampling_Rate = 0.00004; % which means one data point every 0.001 sec Total_Time = 0:Sampling_Rate:1; % An array for time from 0 to 1 sec with 0.01 sec increment Omega = 49.11; % in [rad/s] zeta=0.0542; %unitless Omega_d=49.03; % in [rad/s] Displacement_Amplitude = 6.009; % in [mm] Phase_Angle = 1.52; % in [rad] Total_No_of_Points = length(Total_Time); % equal to the number of points in...
Please fix this code I am having issues compiling it all together there is 3 codes...
Please fix this code I am having issues compiling it all together there is 3 codes here and it's giving me errors in my main method..... I feel like it might be something simple but I can't seem to find it. package assignement2; import java.util.ArrayList; import java.util.Scanner; public class reg1 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter the number of items: "); int number = input.nextInt(); input.nextLine(); for (int i = 0; i <...
Please provide an example of both a Type I Error and Type II Error. Why is...
Please provide an example of both a Type I Error and Type II Error. Why is it that increasing the sample size reduces the probability of a Type II error to an acceptable level. Please discuss.
Hello I have this error in the code, I do not know how to fix it....
Hello I have this error in the code, I do not know how to fix it. It is written in C++ using a Eclipse IDE Error: libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: basic_string bus.h =========== #pragma once #include using namespace std; class Bus { private:    string BusId; // bus ID    string Manufacturer; // manufacturer of the bus    int BusCapacity; // bus capacity    int Mileage; // mileage of bus    char Status; // current status...
I'm Getting an "unindented error" Please fix the bolded codes. Because I don't know whats going...
I'm Getting an "unindented error" Please fix the bolded codes. Because I don't know whats going on. Thank You. # This program exercises lists. # The following files must be in the same folder: # abstractcollection.py # abstractlist.py # arraylist.py # arrays.py # linkedlist.py # node.py # input.txt - the input text file. # Input: input.txt # This file must be in the same folder. # To keep things simple: # This file contains no punctuation. # This file contains...
Hello, I am working on an assignment but I am unsure of how to solve it....
Hello, I am working on an assignment but I am unsure of how to solve it. Please help me. The assignment details are below. Consider this scenario: Your friend starts a website, nothingbutflags.com, which is not making money. Your friend asks you to help generate more traffic. You ask your friend how much traffic the website had last month? And your friend replies and says only 500 visits. You also ask how many flags did you sell? Your friend replies...
Hello, I am working on an assignment but I am unsure of how to solve it....
Hello, I am working on an assignment but I am unsure of how to solve it. Please help me. The assignment details are below. Consider this scenario: Your friend starts a website, nothingbutflags.com, which is not making money. Your friend asks you to help generate more traffic. You ask your friend how much traffic the website had last month? And your friend replies and says only 500 visits. You also ask how many flags did you sell? Your friend replies...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT