简体   繁体   中英

linked list null pointer error c++

i have a project to count from a file. Since it is a school project i am not allowed to use most libraries but basic ones. thus i decided to use hash map. but my linked list gives a null pointer exception. to be precise "Exception thrown: read access violation. this was 0xCCCCCCCC. occurred". i searched a lot to find a solution but i couldn't find anything. Thank you for your time.

public: liste() {
        head = NULL;
        tail = NULL;
    }

    void createnode(string value) {
        liste();
        node* temp = new node;
        temp->data = value;
        temp->next = NULL;

        if (head == NULL) { // get error here!!!!

            head = temp;
            tail = temp;
            temp = NULL;
        }

        else {
            tail->next = temp;
            temp = tail;
        }
    }

        int main()
    {   
        struct site {
            int count;
            string name;
        };  
        unsigned long int i=0;
        unsigned int x=0;
        ifstream theFile("access_log");
        string word;
        liste* table[100000];
        site list[10];

        while (theFile >> word) {   
            if (word.find(".")!=-1) {
                if (word.find("H") == -1) {
                    x=(int)hashG(word);
                    if (x < 100000) {                   
                        table[x]->createnode(word);
                    }
                }
            }

        }
        for (int i = 0; i < 100000; i++) {
            cout << table[i]->length() << "   " << table[i]->getData() << endl;
        }   
        return 0;
    }

Here you create an array of 10000 liste-pointers

liste* table[100000];

but you never create any liste objects for them to point to. Later you want to call the member function

table[x]->createnode(word);

As your pointers in table are still not initialized your call crashes.

My assumption is that you want to have table to be an array of liste objects

liste table[100000];

What I still don't get is why you call liste() (a constructor?) in your createNode function.

apparently not initializing your class array causes this.adding this fixed it.

for ( i = 0; i < 100000; i++)
        {
            table[i] = new liste;

        }

note to self : do not watched tutorials about code implementation if they are telling on board. people might forget things.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM