alperk
alperk

Reputation: 15

Linkedlist Memory Read Error

I'm trying to create a linked list, but I have a problem about memory access. I debug the code, see where it gives error, but cannot solve it. With using 'Add watch', can see the next has unable to read memory error.

struct Node
{
    string Name;
    Node* next;
};

struct LinkedList
{
    Node* head = NULL;
    bool isX = true;
};


LinkedList* initX(string Arr)
{
    LinkedList* link = new LinkedList;
    for (int i = 0; i < 15; i++)
    {
        Node* temp = new Node;
        temp->Name = Arr[i];
        Node* ptr = new Node;
        ptr = link->head;
        if (link->head != NULL)
        {
            while (ptr->next)
            {
                ptr = ptr->next;
            }
            ptr->next = temp;
            temp->next = NULL;
        }
        else
            link->head = temp;
    }
    return link;
}
Unhandled exception at 0x008E8AF7 in ...exe: 0xC0000005: Access violation reading location 0xCDCDCDE9.

How can I solve it?

Upvotes: 1

Views: 938

Answers (1)

David G
David G

Reputation: 96835

After you set link->head to temp in the else part of your if statement, you don't set temp->next to NULL, thus making any use of temp->next as if it had a value in undefined behavior. Add this to your else part:

else {
    link->head = temp;
    temp->next = NULL; // or nullptr
}

It would actually be better if you moved both temp->next = NULL, made them into one, and put it as the last statement in the for loop. That why you don't have to do the same thing for both conditions.

Upvotes: 1

Related Questions