Releasing the same pointer twice without throwing an error if I make a NULL pointer

I tried to delete the same pointer twice, but it failed, but if I follow the same steps without making it NULL, the code works fine.

 #include <iostream>

    struct MyClass {
      MyClass() {std::cout << "Allocated and Constructed" << std::endl ;} 
    };

    int main () {
      // allocates and constructs five objects:
      MyClass * p1 = new MyClass[5];

      delete[] p1;
      delete[] p1; // The code will succeed if I comment this line of code
      p1=NULL;
      delete[] p1;
      delete[] p1;

      return 0;
    }

I see a good answer to the question What happens when you delete a pointer twice or more in C ++? but what makes it run, if I do it NULL, shouldn There shouldnโ€™t be the same behavior for both cases?

+4
source share
3 answers

You need to free only what you highlight. You highlight five instances MyClasswith new[]. So what do you need for liberation.

. , , - .

nullptr ( NULL), . delete . ++ delete ( delete[]) .

+6

delete[] p1; p1. ( ++ , p1 nullptr , , , ).

, delete[] p1; undefined, .

p1 = nullptr a delete[], delete . ( delete ?), .

+1

, 5.3.5 $2 [expr.delete] ( )

( ) delete , , (1.8), (. 10). , undefined. ( ), , new-expression. 81 , undefined.

, UB .

+1

Source: https://habr.com/ru/post/1611551/


All Articles