0

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;
}
Steven
  • 95
  • 5
  • 2
    Your problem is allocation of the second dimension not deletion. This question should help: [https://stackoverflow.com/questions/936687/how-do-i-declare-a-2d-array-in-c-using-new](https://stackoverflow.com/questions/936687/how-do-i-declare-a-2d-array-in-c-using-new) – drescherjm Nov 18 '21 at 16:16
  • You never assign a value to the elements of the array `doublePtrNode` (which are pointers). –  Nov 18 '21 at 16:17
  • Side note: explicit use of `new` and `delete` since C++11 is considered as a bad practice. You should use `std::vector` which will do proper memory management in your behalf. In other cases there is `std::unique_ptr` and `std::shared_ptr`. – Marek R Nov 18 '21 at 17:07

2 Answers2

3

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
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • Thank you, Ted, for your explanation. so when I created the double-pointer array, I just created 10 pointers of Node, Since they are just pointers. I still need to allocate memory to each Node so that they can be used right? – Steven Nov 18 '21 at 16:32
  • @Steven Exactly! Perfect summation. – Ted Lyngmo Nov 18 '21 at 16:33
1

you need create every node doublePtrNode[i] before assign on it value

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


int main()
{

    Node** doublePtrNode = new Node * [10];

    for (int i = 0; i < 10; i++)
    {

        doublePtrNode[i] = new Node{ i,nullptr };

    }

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

    delete[] doublePtrNode;

    return 0;
}
arutar
  • 1,015
  • 3
  • 9