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

delete a double pointer

How to properly delete a double-pointer array? when I tried this code, memcheck told me that "Use of the uninitialized value of size 8" and "Invalid write of size 4". I couldn’t figure out where I did wrong.

struct Node
{
    int value;
    Node* next;
};


int main()
{

    Node** doublePtrNode= new Node* [10];
     
     for (unsigned int i = 0; i < 10; i++)
    {
        
        doublePtrNode[i]->value=i;
        
    }

    for (unsigned int i = 0; i < 10; i++)
    {
        delete doublePtrNode[i];
    }
  
    delete[] doublePtrNode;

    return 0;
}

>Solution :

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

You are already deallocating what you have allocated but doublePtrNode[i]->value=i; assumes that you’ve allocated a Node there, but you haven’t so the program has undefined behavior.

If you are going to use raw owning pointers, you could fix it like this:

Node** doublePtrNode = new Node*[10];
// now allocate the actual `Node`s too:
for(unsigned i = 0; i < 10; ++i) doublePtrNode[i] = new Node;

// your current assigning loop goes here

// deallocate the `Node`s:
for(unsigned i = 0; i < 10; ++i) delete doublePtrNode[i];
delete[] doublePtrNode;

A much simpler and safer option is to use a std::vector<Node>. That way you do not need any manual memory management. It does it for you.

#include <vector>

int main() {
    std::vector<Node> nodes(10);

    // your current assigning loop goes here

} // all `Node`s are deleted when `nodes` goes out of scope
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