The following code has no issues
int* ptr = nullptr;
int* ptr2 = ptr;
Dereferencing a null pointer is where the demons lie. A null pointer is a pointer that doesn’t point anywhere anf dereferencing a pointer means to fetch the value at the address pointed to by the pointer.
Therefore trying to fetch the value at the address of nowhere == bad times.
nullptr
itself is good. Otherwise why would it exist if it just blows things up just using it?
// 1.
int* ptr = new int(5);
int value = *ptr;
// 2.
delete ptr;
// 3
if (ptr != nullptr)
{
int value = *ptr;
}
-
This code creates an int on the heap with the value of 5 and the address of where that is stored is returned and stored in the variable ptr
. The next line fetches the int at the address and stores it in a variable. Nothing wrong so far (basically just a setup for the next two points).
-
delete ptr
says to free that memory so the OS can reclaim that memory.
ptr
now points to invalid memory (not nullptr
). Unless the compiler aided you here It’s the same address it stored previously but the OS has reclaimed that and can now overwrite that area of memory for its own use. Dereferencing this now is a big no no; you don’t know what’s there anymore.
-
This check succeeds! Meaning you then dereference invalid memory . If the code set ptr
to nullptr
after deleting then there would be no issue.
In a nutshell nullptr
, dereferencing nullptr