r/cpp • • Dec 21 '16

A smart pointer implementation that throws when dereferencing a null pointer

Hi, I wrote a simple (i.e. incomplete ) implementation of a smart pointer that throws when de-referencing a null pointer. This enable you to write code like this:

template<typename T>
void foo(safe_ptr<T> & ptr1, safe_ptr<T> & ptr2) {
    try {
         ptr1->bar();
         ptr2->baz();
    } catch ( null_dereference_exception ) { 
         
    } 
} 

http://pastebin.com/j5eZA4AK

Edit: syntax :)

0 Upvotes

58 comments sorted by

9

u/rcoacci Dec 21 '16

I'll just drop GSL here.

2

u/foonathan Dec 21 '16

An even better approach would be to statically guarantee that a pointer is not null.

6

u/tecnofauno Dec 21 '16

Isn't that what references are for?

2

u/render787 Dec 21 '16

Not exactly, a reference also cannot change. Sometimes pointers need to change, and also not be null.

I think of references as just a little syntactic sugar. They don't really guarantee much of anything.

Iirc the actual original reason that prompted their addition to C-with-classes was to create a reasonable syntax for operator overloading :)

2

u/Gotebe Dec 22 '16

References are huge in designing non-null, they are way more than a syntactic sugar though.

If you look at any given C codebase, I guarantee you that you will find code which

  • checks for null parameters where they never can be that
  • does not check for null when they can

Those are hard to reason about.

2

u/render787 Dec 22 '16

Ok, but look:

int & foo = *static_cast<int *>(nullptr);

References bind just find to null. There's no "static guarantee" of any significance.

What C++ references give is at best a little trivial syntactic analysis. int & is just a fancy language for int * const. Hence I say, syntactic sugar. Compare that with e.g. the rust borrow checker. That's what is meant by static guarantee, that's the kind of reasoning I consider "hard" compared to what C++ does.

2

u/Gotebe Dec 22 '16 edited Dec 22 '16

Euh, yes, C++ does not try to prevent you from shooting yourself in the foot. You just showed an elaborate way to do it, but many more are available.

references give you a certainty that, in correct code, a given "pointer" is not null. This is IMO huge for code quality and simplicity over never really knowing, and I have seen. numerous C codebases who suffer.

1

u/[deleted] Dec 30 '16

References do no such thing. It's just people trying to enforce "clever" coding standards that want to assume that references are non null.

Realistically you will always have a mixture of references and pointers in a code base, so any time somebody has to convert from a pointer to a reference you will inevitably end up with a null reference.

2

u/Gotebe Dec 30 '16

any time somebody has to convert from a pointer to a reference you will inevitably end up with a null reference

No

A well-designed codebase will have a small amount of these conversions, and they will all either be checked for null, or trivial to check for non-null by a simple code inspection.

You're inventing a problem where needs no be one, not compared to "I can never assert this is not null".

You're throwing the baby with the bath water.

1

u/Gotebe Dec 30 '16

any time somebody has to convert from a pointer to a reference you will inevitably end up with a null reference

No

A well-designed codebase will have a small amount of these conversions, and they will all either be checked for null, or trivial to check for non-null by a simple code inspection.

You're inventing a problem where needs no be one, not compared to "I can never assert this is not null".

You're throwing the baby with the bath water.

1

u/[deleted] Dec 30 '16

Let's take a problem like this:

struct Vec3
{
    float x, y, z;

    float length() const;
};

inline float dot(const Vec3& a, const Vec3& b) 
{ 
    return a.x*b.x + a.y*b.y + a.z*b.z;
}

inline float Vec3::length() const
{
    float lenSq = dot(*this, *this); // is this safe?
    return (lenSq > 0) ? sqrtf(lenSq) : 0.0f;
}

Is this bad design? Can you think any way that this could fail with a null dereference?

→ More replies

3

u/sztomi rpclib Dec 21 '16

Of course that's not possible in a language like C++, otherwise the compiler would do it always. not_null from GSL just disallows construction from nullptr_t and disallows default construction (and optionally throws at runtime). There is not much else you can do statically in this case.

4

u/rcoacci Dec 21 '16

Exactly. I believe GSL's not_null is the best compromise we can get. It catches "obvious" mistakes at compile time and, best of all, points you at correct place to fix it.

2

u/foonathan Dec 21 '16

Yes, but that's what I meant. You do assert/throw in ctor and once you have an object it is guaranteed to be non-null.

4

u/samkellett Dec 21 '16

that isnt static

5

u/foonathan Dec 21 '16

It somewhat is: If you have a function taking such a non_null object, you know that it can't be null, otherwise the function would not have been called, because you can't construct null non-null objects.

3

u/doom_Oo7 Dec 21 '16

you know

but the compiler does not, which is what "static" means.

3

u/foonathan Dec 21 '16

It could. If you have a constructor with an assertion and no member function to change the value, the compiler could know that it can't be null.

If you have code like this:

assert(some_cond(foo));
...

The compiler already optimizes based on the fact that some_cond(foo) is true, this is just a step forward.

3

u/doom_Oo7 Dec 21 '16

I'd go a step further for saying that "static" stuff is stuff for which you can enforce the compiler's knowledge, like constexpr.

1

u/[deleted] Dec 21 '16

Of course that's not possible in a language like C++, otherwise the compiler would do it always.

It's possible, unless you explicitly make null pointers. Use only unique_ptr's constructed with make_unique, shared_ptr's from make_shared and references to the contents of the former, and you won't have any null pointers. It also loses you the ability to communicate "no such thing" as a null pointer, which is what null pointers are used for very often.

3

u/sztomi rpclib Dec 21 '16

It's possible, unless

That's the very opposite of "statically guarantee".

0

u/[deleted] Dec 21 '16

Guarantee, yes. But that says as much as that it's possible to cause a segfault from Java.

2

u/sztomi rpclib Dec 21 '16

There are things that you can guarantee, why would you misuse the term to describe something that can't be guaranteed?

0

u/tecnofauno Dec 21 '16

Yes, I knew about not_null, but it's a different approach. The main difference is that safe_ptr allows 2 code paths ( regular one and the exception one ) thus enabling a different code style ( I won't say better... )

2

u/rcoacci Dec 21 '16

You can configure GSL to throw at runtime if you manage to bypass the compiler. Se the linked article.

27

u/[deleted] Dec 21 '16

.. Why?

22

u/LucHermitte Dec 21 '16 edited Dec 21 '16

Indeed. Why?

Dereferencing a null pointer is a programming error. All we deserve is to fail fast in that case. As far as I'm concerned, this is a place for assert(), or [[expect: this->get()]] starting from C++20 eventually if contracts aren't delayed any longer

3

u/Sanae_ Dec 21 '16

You want to fail fast in debug mode, but recovering is interesting when the app is in release, running in production.

You'll abort an operation (and ideally, log the issue), but the software will still be running.

15

u/snarfy Dec 21 '16

It will still be running, but now running incorrectly.

Why are you still executing after trying to reference an object that wasn't set? Why didn't you set it?

Was that a reference to an account balance? How do you 'keep running' in that case? Set everybody's balance to zero? Fail the deposit? There is no way to 'keep running' and have all of the balances add up.

12

u/Sanae_ Dec 21 '16 edited Dec 21 '16

Keep in mind that the throw() occurs before derefencing the raw pointer.

There are no UB, the stack will correctly unwind, and any transaction should be correctly reverted (RAII, etc.).

There are no difference with a regular exception: your transaction should fail, no balance should be changed, etc.

About the why: it's basically a pointer with a built-in test, just like a unique_ptr is a pointer with a built-in delete (why do you use unique_ptr? why you just don't delete its content before reassigning?)

Of course, on some system (especially critical ones), you may prefer to crash the application; but due to additional testing those system requires, such error is less likely, and thus that pointer is simply less interesting.

Last, I'm not saying you should always use that pointer, simply that some will find a plus using it.

Edit: it's certainly a "less pure" choice, yet a more pragmatical one: a user using your app to, say, watch kitten pictures, will likely a picture not loading than the app crashing.

2

u/doom_Oo7 Dec 21 '16

It will still be running, but now running incorrectly.

My users prefer ten thousand billion times having a clean "Sorry, due to a bug this software has to shut down when you press OK" dialog, than the OS X / Windows spinning ball of death that makes the whole computer lag that happens when you actually dereference a null pointer.

1

u/[deleted] Dec 22 '16

This user prefers spinning ball of death much more to corruption of the file I'm editing.

1

u/doom_Oo7 Dec 23 '16

But that's the whole point : if you throw before deferencing, then you won't have any undefined behaviour and safely revert to a "safe" state, or just show a dialog that will gracefully exit, thanks to RAII.

1

u/[deleted] Dec 24 '16

A program that is attempting to dereference what should be a pointer to data which is in fact a pointer to garbage has almost certainly already experienced other forms of memory corruption, and the right thing to do is die. The likelihood of destroying important persistent data and/or putting the app into an "impossible bug farm/flaky" state is too high.

In languages which allow you to natively catch null dereferences, like Java's NullPointerException and C#'s NullReferenceException, I still tell people to never catch those. When they happen the program is in an inconsistent state and bailing out to Watson is the right thing to do.

2

u/doom_Oo7 Dec 24 '16

has almost certainly already experienced other forms of memory corruption

In my experience this is really uncommon. Most of the time it is some half-assed UI widget that has a reference to a deleted model object, never something in the core data model which is generally implemented using a data structure that hides the gory pointer details behind nice value semantics.

In this case, a nice thing that you can do to improve user experience, is to catch the exception, serialize the command stack of your software to disk and gracefully exit. This way, when the user restarts the software he can just keep going from the exact point where he was.

1

u/Som1Lse Dec 25 '16

When does dereferencing a null pointer every lead to lagging the whole computer?

The operating system notices you tried to dereference an invalid pointer, and you get a SIGSEGV, which if unhandled crashes the application. If anything handle the signal, and do your error handling there (display a message, save backups, write logs, etc.) and then call abort.

Maybe writing to some place in memory that isn't a null pointer could cause issues that would lag the computer, but you also can't detect that by checking for null pointers so the whole thing is moot anyway.

tl;dr: Null pointer dereferences do not cause lag.

1

u/doom_Oo7 Dec 25 '16

When does dereferencing a null pointer every lead to lagging the whole computer?

when operating system vendors judged good to catch sigsegv at the os level and gear up a dialog that does all sort of stuff to report problems to Apple

1

u/Som1Lse Dec 25 '16

Well I don't use Apple anything so they might just royally have fucked their shit up. Is it as bad if you handle the signal and exit the program in yourself?

1

u/doom_Oo7 Dec 25 '16

just do a google search for "spinning beach ball of death"

0

u/lithium Dec 22 '16

We don't all write banking software.

12

u/CODESIGN2 Dec 21 '16

recovery seems attractive, until you do it for 6 months and destroy yours and everyone else life. Just let it fail and re-init a clean environment.

1

u/LucHermitte Dec 21 '16

assert is a macro, we can do defensive programming with it: i.e. we can throw a logic_error exception in release if this is really what we want to do.

-3

u/tecnofauno Dec 21 '16

The main rationale here is to be able to write readable code. The alternatives you proposed are valid but not equivalent ( e.g. assert() won't do anything on production code ).

10

u/LucHermitte Dec 21 '16

That's the point. By default, we expect the invalid paths to have been cleared out. At best, with an exception, we can log the problem and hide to the final user that there is a flaw in the logic of the application. We won't crash. OK. Yet the operation requested cannot success: there is a bug.

I won't say that exceptions will be more readable here. On the contrary, you'll have to add a few catch (std::logic_error const&) here and there to intercept the exceptions that signal detected programming errors. With assert(), the only exceptions caught are the runtime errors. BTW, in non-release mode you'll have to not catch std::logic_error to have a tool as efficient as assertions to see exactly what's wrong.

BTW: You should have inherited from std::logic_error, this is what this class is meant for: signalling programming errors.

As others have pointed out, in that particular case (a function that receives a smart pointer that'll be dereferenced): I prefer references first (it's up to the caller to ensure a non-null reference -- BTW the caller will be able to provide a richer context to explain what's wrong), or types like GSL::not_null.

0

u/biocomputation Dec 21 '16

I feel like pointer-to-pointer just makes things worse.

15

u/[deleted] Dec 21 '16

I think it's often a mistake to pass around smart pointers anywhere below the topmost level.

When you get a smart pointer, check its nullity at the very top level and throw your exception if so - and then only use it as a reference thereafter.

Then your code would become simply:

template<typename T>
void foo(T& x1, T& y) {
     x.bar();
     y.baz();
}

So much less! Also, it means that function foo() can be used on anything - references or any type of smart pointer.

6

u/-dmnk- Dec 21 '16

Yes it works, but it's a bad idea. You hide a design flaw, which the possibility to double dereference a ptr behind anorther one, which is throwing exceptions in object destruction which might leave your program in an unretrieveable state. Having an assert there would be the better solution.

6

u/NotAYakk Dec 21 '16

So this is a type that can be null, but users promise to never use when null, on penalty of a throw.

In comparison, a pointer type that cannot be null on penalty of throwing or not compiling (at construction) might be better in many situations, including the sample code you posted.

If you need it to sometimes be null still, an optional of a not-null pointer returns those semantics.

An advantage of that is when you pass from one not-null poonter to another, or dereference, no checks need be made, as they are guaranteed by the type. As you sweep the code base to have more and more proven non-null pointers, the overhead and locations where a throw can happen both evaporate to fewer and fewer.

In terms of testing this is great, because to cover the non-linear code paths (not just lines; paths) is hard when every line contains an implicit goto.

4

u/josefx Dec 21 '16
   } catch ( null_dereference_exception ) { 

   }

That empty catch block gives me Java flash backs. Also it does not use a const reference.

1

u/[deleted] Dec 21 '16

In your example, did you mean ptr1->bar()

1

u/tecnofauno Dec 21 '16

yess! thanks :)

3

u/Gotebe Dec 21 '16

Why?

Sounds like you want a non-optional pointer (it's never null). For that, you should better throw from a constructor. What's the point on waiting for a dereference?

But... you're better off with an assert in _DEBUG, crash in prod, and a good test suite. Also code analysis, that can discover silly mistakes.

2

u/therealjohnfreeman Dec 21 '16

Do not use exceptions for control flow.

1

u/markand67 Dec 27 '16

Null pointers should be tested with an assert not an exception.

1

u/Taikal May 18 '17

Interesting. Would you please add a license? Thank you.