Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't delete node from node list

I have a little problem which occurs after trying to execute function delete_all(). Any idea why Visual Studio is throwing me an error:

Invalid address specified to RtlValidateHeap, instruction __debugbreak() or something similar

Everything works perfect until I want to execute this function.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#include <iostream>

using namespace std;

struct node {
    string name = "n1";
    node* prev = NULL;
    node* next = NULL;
};

node* add(node* first, string name) {
    if (first == NULL) {
        return NULL;
    }

    node* nowy = new node;

    if (first->next == NULL) {
        nowy->prev = first;
        first->next = nowy;
    }
    else {
        while (first->next != NULL) {
            first = first->next;
        }
        nowy->prev = first;
        first->next = nowy;
    }

    nowy->name = name;

    return nowy;
}

void writeout(node* first) {
    if (first == NULL) cout << "first = NULL";

    while (first->next != NULL) {
        cout << first->name;
        cout << "\n";
        first = first->next;
    }

    if (first->next == NULL) {
        cout << first->name;
        cout << "\n";
    }
}

void delete_all(node* first) {
    node* temp;
    while (first != NULL) {
        temp = first->next;
        delete first;
        first = temp;
    }
}

int main()
{   
    node n1;

    add(&n1, "n2");
    add(&n1, "n3");

    writeout(&n1);

    delete_all(&n1);
}

>Solution :

You declared an object in main() with automatic storage duration as the first node of the list:

node n1;

You may not destroy it using the delete operator.

Using your approach of the list implementation, you could define the function delete_all() the following way:

void delete_all(node* first) 
{
    if ( first != nullptr )
    {
        while ( first->next != nullptr ) 
        {
            node *temp = first->next;
            first->next = temp->next;
            delete temp;
        }
    }
}

But, it will be much better if initially in main(), you declared a pointer to a node. In this case, you will need to update the functions.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading