jeudi 8 septembre 2022

Problem in Deleting the elements of an array allocated with new[]

This question is similar to Problem with delete[], how to partially delete the memory?

I understand that deleting an array after incrementing its pointer is not possible as it loses the track of how many bytes to clean. But, I am not able to understand why one-by-one delete/deallocation of a dynamic array doesn't work either.

int main()
{
    int n = 5;
    int *p = new int[n];
 
    for(int i=0;i<n;++i){
        delete &p[i];
    }
}

I believe this should work, but in clang 12.0 it fails with the invalid pointer error. Can anyone explain why?

Aucun commentaire:

Enregistrer un commentaire