Search code examples
c++visual-studionodes

getting error Exception thrown: read access violation


I am currently working with an array of Node pointers. I want to make a node at that index (aBet[]) if that index of that Node array is pointing to null. However I get an **error on the if statement that says: "Exception thrown: read access violation. Node was 0x1110112."

I also made a default constructor to make the values in the array point to Null:

Lib::Lib()
{
    // establishes an empty node
    Node* r = new Node;
   for (int i = 0; i < MAX_LETTERS; i++)
   {
    root->aBet[i] = nullptr;
   }

}

struct Node {
    Node* aBet[MAX_LETTERS];
 };

I have also created a node as well.

Node* ode;
int charPos;
ode = r;

for (int i = 0; i < word.length(); i++) 
{
    charPos = (int)word[i] - (int)'a'; 
    
    if (ode->aBet[charPos] == nullptr) // an error is here**
    {
        Node* newBranch = new Node;

Why do I keep getting this error?


Solution

  • you do not initialize currNode so currNode->aBet has an undefined behavior

    [edit after remarks]

    Your definitions are strange, for me aBet must be an attribute of Dict rather than of Node, also currently Node is quite useless because only memorize pointers to Node

    If you just want to memorize words you just need to define the class Dict, for instance :

    class Dict {
       private:
         std::list<std::string> aBet[MAX_LETTERS];
       ...
    };
    

    if you want to also have a definition for each word :

    class Word {
      private:
        std::string name;
        std::string definition;
      ...
    };
    
    class Dict {
       private:
         std::list<Word> aBet[MAX_LETTERS];
       ...
    };
    

    you do not have to manage the list by hand, we are not in C, better use features from std

    note your Dict can be replaced by a std::map<std::string, std::string> where each key is a word and the value its definition ;-)