Hello,

Please help me to overcome the following confussion.
Suppose I have created an array of pointers like,

A** l_aAPtr = new A*[l_iTotal];
for(int i = 0; i<l_iTotal;i++)
{
    l_aAPtr[i] = new A();
}

Now I want to delete this array. Please advise which of the following way is correct

1.

for(int k = 0; k<l_iTotal;k++)
{
    if(l_aAPtr[k])
    {
            delete l_aAPtr[k];                
            l_aAPtr[k] = 0;
    }
}
if(l_aAPtr)
{
    delete l_aAPtr;           
    l_aAPtr = 0;
}

2.

for(int k = 0; k<l_iTotal;k++)
{
    if(l_aAPtr[k])
    {
            delete l_aAPtr[k];                
            l_aAPtr[k] = 0;
    }
}
if(l_aAPtr)
{
    delete [] l_aAPtr;           
    l_aAPtr = 0;
}

Thanks in advance,

Amit M.

Dani AI

Generated

and are correct, and here are the practical reasons and safer alternatives to consider.

When you allocate A* pointers with new A*[n] you must free that pointer-array with delete[] (mixing new[] and delete is undefined). Also remember that delete[] on the pointer-array only releases the block that contained the pointers; it does not delete the A objects those pointers point to. So you must delete each A instance first, then delete[] the array of pointers. Checking a pointer for null before calling delete is unnecessary because delete on a null pointer is safe; however, calling delete on an uninitialized or already-deleted pointer is undefined behavior, so keep initialization and ownership clear.

A few practical cautions and improvements:

  • If A will be used polymorphically (deleting through a base pointer), ensure A has a virtual destructor.
  • The code that repeatedly does new A() in a loop can leak if one allocation throws; prefer RAII so partially-constructed resources are cleaned automatically.
  • Prefer standard containers and smart pointers instead of manual new/delete. For example, a safe modern pattern is:
std::vector<std::unique_ptr<A>> vec;
vec.reserve(n);
for (int i = 0; i < n; ++i)
    vec.emplace_back(std::make_unique<A>()); // C++14; for C++11 use vec.emplace_back(new A());

This removes the need for manual deletes, avoids leaks on exceptions, and makes ownership explicit. If you truly need a contiguous array of A objects, use std::unique_ptr<A[]> or std::vector<A> instead.

Recommended Answers

All 3 Replies

The second is more correct. When you say new[], you should use delete[], when you say new, you should use delete. They can't be mixed and matched.

The second one is because l_aAPtr is an array.

Thanks a lot.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.