Should I use ‘delete’ in the following example?
int main(){
T object;
T* pointer = new T[4];
delete[] pointer; // this line is redudant? or error?
pointer = &object;
}
I’m asking Chat GPT this same question and it says: "the line delete is redudant and may lead to undefined behaviour, because when you re-assign the pointer, the data on heap is automatically deallocated". But i have a doubt about this. So should I use ‘delete’ there?
>Solution :
"the line delete is redudant and may lead to undefined behaviour, because when you re-assign the pointer, the data on heap is automatically deallocated"
This is utter nonsense.
What you create via new you must eventually be deleted via delete (and delete [] for what has been allocated via new []). The line does not lead to undefined behavior. It is also not redundant, because if you do not delete the array you have a memory leak. Reassinging the pointer does not deallocate the memory it was pointing to.
It should be noted that you should not use new in the first place. Raw owning pointers are dangerous and will lead to problems. Use std::vector, other containers, and smart pointers for dynamic memory managment, but don’t do it manually.