Hello there!
So if you dereference a null pointer accessing a function of class for example like:
SomeClass *p = nullptr;
p->DoSomething();
This can work perfectly fine as long as the function doesn't touch member variables.
Or even worse something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
|
#include <iostream>
int g_iGlobalInt = 0;
float g_flGlobalFloat = 0.0f;
class Test
{
public:
void SetFloatAndInt()
{
// m_p is uninitialized, and 'this' is nullptr
m_p->SetInt();
m_p->SetFloat();
}
protected:
void SetInt()
{
g_iGlobalInt = 378;
}
void SetFloat()
{
g_flGlobalFloat = 222.0f;
}
private:
Test *m_p;
};
int main()
{
Test *p = nullptr;
p->SetFloatAndInt();
std::cout << "g_iGlobalInt is: " << g_iGlobalInt << std::endl;
std::cout << "g_flGlobalFloat is: " << g_flGlobalFloat << std::endl;
std::cin.get();
return 0;
}
| |
Which CAN work due to compiler optimization. (Like building in Release mode, this would crash in Debug mode)
To me this is kind of garbage and it can make it harder to track down the actual cause of a crash because there's some operation done on a bogus pointer somewhere which can be caused by accessing a null pointer like in the example above.
To me if the above behavior is working, that is bad, that is most definitely not something I want.
This is sort of platform specific as far as I know, but I figured I'd ask anyway.
Is there any way to better guarantee desired behavior? I would like it to crash.