Force Null Pointer Derefs to Crash?

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.
Last edited on
wrap it on your own pointer class that does make checks
GCC and Clang has -fsanitize=null which will add checks for null pointers.

test.cpp:36:19: runtime error: member call on null pointer of type 'struct Test'
test.cpp:13:3: runtime error: member access within null pointer of type 'struct Test'


https://gcc.gnu.org/onlinedocs/gcc/Instrumentation-Options.html#index-fsanitize_003dnull
This option enables pointer checking. Particularly, the application built with this option turned on will issue an error message when it tries to dereference a NULL pointer, or if a reference (possibly an rvalue reference) is bound to a NULL pointer, or if a method is invoked on an object pointed by a NULL pointer.
Last edited on
Wrapping it in my own pointer class wouldn't be feasible with an existing rather large application in terms of the codebase.

It's also built with the Microsoft C++ compiler, though I have been interested in clang. I have no idea how difficult it would be to switch everything over. But seeing things like clang-tidy has got me sort of interested.
Topic archived. No new replies allowed.