Update: I have been digging in various ways to come to a better understanding of the picture I have demonstrated below(a deliberately buggy program!). I am still learning but hate to move forward with a misunderstanding in my brain. I have found the following link and it seems to lead in a promising direction:
conversion from nullptr_t to bool: valid or not?
I tried testing memory allocated with new and ran into unexpected behavior. I have created code to demonstrate:
#include <iostream>
#include <new>
using namespace std;
int main()
{
// This section is checking the supposed nullptr assigned when memory allocation fails.
int i = 2000000000; // Within range of long values.
int * p2 = new (nothrow) int[i];
cout << "Allocation innappropriate amount of memory and getting nullptr?" << endl << endl;
cout << "Pointer address: " << p2 << " --- Value at pointer address: " << *p2 << endl << endl;
if(p2)
{
cout << "True - Pointer address: " << p2 << " --- Value at pointer address: " << *p2 << endl << endl << endl;
}
else
{
cout << "False -Pointer address: " << p2 << " --- Value at pointer address: " << *p2 << endl << endl << endl;
}
// This section is checking how nullptr looks in gcc.
int * p1 = nullptr;
cout << "Assigning nullptr to pointer varialble." << endl << endl;
if(p1)
{
cout << "True - Pointer address: " << p1 << " --- Value at pointer address: " << *p1 << endl << endl << endl;
}
else
{
cout << "False -Pointer address: " << p1 << " --- Accessing value would cause error!" << endl << endl << endl;
}
}
The output is:
Allocation innappropriate amount of memory and getting nullptr?
Pointer address: 0x1f70783e040 --- Value at pointer address: 0
True - Pointer address: 0x1f70783e040 --- Value at pointer address: 0
Assigning nullptr to pointer varialble.
False -Pointer address: 0 --- Accessing value would cause error!
Process returned 0 (0x0) execution time : 0.096 s
Press any key to continue.
I can't boolean test the pointer in the second part without dereferencing the pointer which I understand isn't supposed to be necessary. Is this just different interpretation of the standard or is this a bug?
Finally figured out a couple of things that were causing me confusion.
When you input a number that is too large for the variable(in this case an int) then the maximum value of int seems to be stored in the variable. This allows the program to continue running using this variable.
This value is still messes up std::cin and it goes into an infinite loop. Apparently a fail flag gets set and it can be reset with cin.clear().
I thought this was a problem with pointers. It is instead a case of how c++ will let you be very stupid.