rsp rsp - 9 months ago 30
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<<"Not NULL"<<endl;
return 0;

After deleting dynamic allocated memory using
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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download