rsp rsp - 2 months ago 10
C++ Question

Why compilers do not assign NULL to pointer variable automatically after deleting dynamic allocated memory?

I have small piece of code:

#include <iostream>
using namespace std;

int main()
{
int *p = new int(10);

if(p != NULL)
{
cout<<"Deleted dynamic allocated memory"<<endl;
delete p;
}

if(p == NULL)
{
cout<<"NULL"<<endl;
}
else
{
cout<<"Not NULL"<<endl;
}
return 0;
}


After deleting dynamic allocated memory using
delete
operator, Why compilers do not assigned NULL to pointer(like p = NULL) automatically?

Answer Source
  1. It would often be unnecessary, particularly in well-written code.

  2. It could hide away bugs.

  3. delete p; would be syntactically idiosyncratic if it modified its argument.

On (1) it would be particularly wasteful with std::unique_ptr.

In other words, burdening the programmer with this job if necessary is the right thing to do.