-1

Look at the line: while(node->next!= nullptr). This code gives me a bad alloc error.

However, when it is changed to while(node!= nullptr), it runs fine. Can someone explain why this error occurs?

void deleteNode(SNode <Object>* & node, Object given)
{
    SNode <Object>* temp= node;
    if(node->data== given)
    {
        node= node->next;
        delete temp;
        temp= nullptr;
    }
    while(temp->next!= nullptr) //this the problematic line
    {
        if(temp->next->data== given)
        {
            SNode<Object>* t= temp->next;
            temp->next= temp->next->next;
            delete t;
            t= nullptr;
        }
        temp= temp->next;
    }
}
Boann
  • 48,794
  • 16
  • 117
  • 146
Avantika P
  • 11
  • 2
  • 2
    What's the exact error? And are you sure `temp` isn't null? It looks like it would be. – Carcigenicate Jun 22 '19 at 18:02
  • Other than the different name, `node` is no different from any `next` . If you abstract away the name, this function becomes much easier to write. [See the community addition linked here](https://stackoverflow.com/a/22122095/4581301) – user4581301 Jun 22 '19 at 18:19

2 Answers2

2

The variable temp is probably a nullptr, so when you try to access it's next member crashes.

One solution is to change that line to while(temp != nullptr && temp->next!= nullptr) to fix the crash.

Silvano Cerza
  • 954
  • 5
  • 16
0

Potentially, the problem is this right here:

    if(node->data== given)
    {
        node= node->next;
        delete temp;
        temp= nullptr;
    }

temp is now possibly a nullptr. Trying to access a member of a nullptr will cause your program to crash.

The simplest solution is to add an else to your code:

    SNode <Object>* temp= node;
    if(node->data== given)
    {
        node= node->next;
        delete temp;
        temp= nullptr;
    } else {
        while(temp->next!= nullptr) //this the problematic line
        {
            if(temp->next->data== given)
            {
                SNode<Object>* t= temp->next;
                temp->next= temp->next->next;
                delete t;
                t= nullptr;
            }
            temp= temp->next;
        }
    }

Although, if node is nullptr for any reason, that would still cause your program to crash, so you are probably just best off checking temp first anyway:

    SNode <Object>* temp= node;
    if(node->data== given)
    {
        node= node->next;
        delete temp;
        temp= nullptr;
    }

    if(temp != nullptr) {
        while(temp->next!= nullptr) //this the problematic line
        {
            if(temp->next->data== given)
            {
                SNode<Object>* t= temp->next;
                temp->next= temp->next->next;
                delete t;
                t= nullptr;
            }
            temp= temp->next;
        }
    }

This has the advantage of not crashing even if nullptr is passed into the function to begin with.