Search code examples
c++pointersdynamic-memory-allocation

Deleting a dynamic array of pointers in C++


I have a question concerning deleting a dynamic array of pointers in C++. Let's imagine that we have a following situation:

int n;
scanf("%d", &n);
Node **array1 = new Node*[n];
/* ... */

where Node is a certain structure defined beforehand. Suppose that after allocation with the new operator, we change the content of the array1 (but we do not delete anything!). What is the proper way to delete the array1 and all its content if there is a possibility of repeated pointers in the array (without sorting them or inserting into the set, in linear time)?


Solution

  • Using this allocation:

    Node **array1 = new Node*[n];
    

    The contents of array1 are undefined. Each element is a Node*, and because the memory is uninitialized, the value could be anything.

    Allocating an array of pointers does not construct objects of the pointed-to class.

    So whatever pointers you put into the array, the objects they point to need to be constructed and destructed elsewhere.

    So to answer your question, the proper way to delete array1 is

    delete[] array1;
    

    However, note that this will not result in destructors being called for each Node* - you should deal with whatever you put into the array before you delete the array.

    EDIT: I was confused by the original question, which mentioned "change the value" in the array, as if there was a valid value in the array as allocated in your example.

    BUT... now that I understand you want to keep track of the pointers for deletion later, perhaps you can just create another array for that purpose where each pointer exists only once. So you have the array you currently have above, which contains pointers to nodes that might be repeated, for whatever purpose you're using it. Then you have another array for the express purpose of managing the deletion, where each pointer occurs only once. It should be easy enough to set something like nodeCleanupArray[i] = pNewNode right after pNewNode = new Node(), then you can blast through that array in linear time and delete each element. (Which means you wouldn't bother inspecting the elements in array1, you'd rely on nodeCleanupArray for the cleanup)