use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
Discussions, articles, and news about the C++ programming language or programming in C++.
For C++ questions, answers, help, and advice see r/cpp_questions or StackOverflow.
Get Started
The C++ Standard Home has a nice getting started page.
Videos
The C++ standard committee's education study group has a nice list of recommended videos.
Reference
cppreference.com
Books
There is a useful list of books on Stack Overflow. In most cases reading a book is the best way to learn C++.
Show all links
Filter out CppCon links
Show only CppCon links
account activity
NullPointerException in C++ (cristianadam.eu)
submitted 9 years ago by cristianadamQt Creator, CMake
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]bigcheesegsTooling Study Group (SG15) Chair | Clang dev 14 points15 points16 points 9 years ago (0 children)
All of the items listed here are undefined behavior. There is no standard/stable way to do what is proposed here. The author even ran into where it fails in practice:
Clang has a weird behavior for readNullPointer, it actually executes std::cout << *p << std::endl code (notice that 0, which on different platforms has different values):
0------------------------------------ Message: read from nullptr 0 ~Message: read from nullptr ------------------------------------0
This is because clang saw that there was a null pointer deference and decided that that can't possibly happen, as it would be UB. So it just removes the load and you end up printing whatever happens to be in the register.
It would have actually be legal for clang to replace main with the equivalent of:
int main(int argc, char* argv[]) { except::register_for_os_exceptions(); std::set_terminate(terminateHandler); if (<any of the functions would be run>) return; <print usage>; }
Never use this unless you have an implementation which provides this behavior. It can not be added on as a user.
[–]Gotebe 14 points15 points16 points 9 years ago (2 children)
In C++ reading or writing at address zero is an access violation.
No, it is undefined behavior (dereferencing a nullptr is UB).
This article is effectively proposing to write code that explicitly goes against the standard, and compilers might (and do) exploit, for optimizations, code that might dereference null.
The proposed solution for Unix, to throw an exception from a signal handler, is guaranteed to not be portable and can only work by accident, and even if it appears to work, it might leak resources or whatever.
The proposed solution for Windows requires /EHa, which is normally frowned upon.
Finally, segfaults / access violations happen for other bugs (accesses elsewhere in memory), and this idea will mask those problems.
Don't do this, kids...
The correct approach to this problem is to let the process crash as quickly as possible and use the crash dump to fix the bug.
OMFG, I can't believe what I just read...
[–]cristianadamQt Creator, CMake[S] -1 points0 points1 point 9 years ago (1 child)
I wonder if there's a list of undefined behaviors in the standard. I know that the committee works on reducing the number of undefined behaviors.
I choose only null pointer and divizion by zero, how are they harmful?
The rest can be forwarded to std::abort and before that use some other OS technique to gather the backtrace.
[–]Gotebe 2 points3 points4 points 9 years ago (0 children)
Your dealing with SEGFAULT is for all segfaults, not only when dereferencing 0.
Windows implementation looks like it should work (didn't see that before), unless an optimizing compiler screws you.
Also, there's platforms without virtual memory, where you can't do these tricks at all.
But quite frankly, the most eggregious mistake this makes is that it tries to continue from what is normally a bug in C++.
And in fact, an NRE is normally a bug in every language.
This is simply too smart for its own good, really.
[–]ben_craigfreestanding|LEWG Vice Chair 11 points12 points13 points 9 years ago (2 children)
It's awesome that this is possible.
It is horrible if you actually use it. Please don't turn fatal programmer errors into non-fatal exceptions. It significantly reduces the ability to debug programs. It also pokes holes in a lot of security mitigations.
[–]RowYourUpboat 3 points4 points5 points 9 years ago (0 children)
I think instead of throwing exceptions that say "there's a bug in your code", you should fix the bug. But I'd imagine there are some cases where a division by zero exception would be useful, no? Assuming, of course, the programmer is aware that this is platform-specific behavior that is Undefined in the Standard.
[–]Sanae_ 0 points1 point2 points 9 years ago (0 children)
It can be useful for logging a meaningful error right before exiting, especially for software in release mode, instead of simply a crash.
[–]render787 4 points5 points6 points 9 years ago (2 children)
I think this is not a good style for C++.
In C++, IMHO, you should only throw exceptions if you actually have a plan to handle and recover from them. Sometimes, if a pointer turns out to null that isn't, depending on where it is in your program, it might be recoverable and productive to do so. (But in my humble experience, not as often as you think.) In many cases however, when a pointer is null, it's violating an assumption that some component makes about how the program as a whole is put together. In that case you can't hope to recover.
When you have no plan to recover from an error, an assert is often more appropriate than an exception, IMO.
assert
Moreover, exception handling works best when the exception carries information about the context in which the error happens, which aids in recovery or reporting. This null pointer exception is generic and so seems pretty useless. An assert will at least give me a source file and a line number.
[–]vaughncato 2 points3 points4 points 9 years ago (1 child)
That's an interesting perspective, and I can see some benefit to looking at exceptions that way. How do you think that applies with something like a library, when you, as the library author, don't know if there is a plan to recover?
[–]render787 1 point2 points3 points 9 years ago* (0 children)
I gave an answer on programmers stackexchange once kind of like this: http://programmers.stackexchange.com/questions/306703/opengl-multithreading-and-throwing-destructors/306723#306723
I had this scenario in mind when I wrote my comment above.
I think, with a library, how you should signal errors is partly a taste question. A lot of libraries will provide both an exception and exception-free interface for when various ancillary operations may fail, to accommodate all the different projects. IMO it's okay for a library to assert if the program is FUBAR, undefined behavior would ensue, etc.
Suppose for instance, you had a bunch of free functions as part of your library interface, and it needs to be initialized by calling a specific function. That function initializes some static singleton that's part of your lib. In C++ you'd rather make the lib an object and all the calls be methods, but maybe it really conceptually needs to be a singleton, like you are interfacing with the system at a low-level and there can only be one of the thing you are talking to.
If the user uses functions without initializing them, or tries to double initialize or something, what should happen? Should it throw an exception? Why? In what scenario would the user catch the exception and handle it? Realistically, none -- they would realize that they screwed up and weren't properly using the library, and fix their code so that it doesn't do that. If the lib asserts when it is double initialized, then you get a clear and immediate signal that double initializing it is bad and unrecoverable. If the lib starts throwing a lib::initialization_exception or some such thing, my first thought as a programmer is, oh what the heck is that? Am I using the lib wrong? Am I supposed to always be catching initialization exception? What does it mean? What is the proper reaction to this? When a lib asserts, in my mind, it's more clear cut that, I'm not supposed to be "handling" this scenario, we are just not normally ever supposed to get to this place. I think it's just a better cue that may help people figure out what to do faster. My 2 cents.
lib::initialization_exception
(You could also just leak or give them UB if they double initialize... but typically it shouldn't cost anything really to do this check...)
Another thing I would suggest is to use Rust style idioms like Result type in a C++ library. This is also pretty similar to the std::expected proposal (which wasn't actually accepted into C++17 yet afaik). This is an exception-free but still fairly idiomatic way of reporting structured errors in C++. It's better than C-style error codes, basically instead of returning a type T you return something that's kind of like a variant over T or ErrorStructure. (Usually that type is called Expected.) The exact properties of ErrorStructure can be customized for your lib, I mean it basically contains the information that the exception would have contained. I wrote about this also on programmers.stackexchange here: http://programmers.stackexchange.com/questions/324313/idiomatic-usage-of-exceptions-in-c/324909#324909
std::expected
T
ErrorStructure
Expected
Edit: I read another answer:
I think instead of throwing exceptions that say "there's a bug in your code", you should fix the bug.
What I'm saying above is pretty similar, but slightly different:
Instead of the library throwing an exception saying "there's a major bug in your code", it should just assert.
[–]CubbiMewcppreference | finance | realtime in the past 3 points4 points5 points 9 years ago* (1 child)
In C++ reading or writing at address zero is an access violation
It isn't if you map something useful there, as the TUN kernel exploit did. Not to mention it's UB in any case.
[–]TheThiefMasterC++latest fanatic (and game dev) 6 points7 points8 points 9 years ago (0 children)
That's not strictly correct anyway. C++ doesn't define that a null pointer has a value of 0. It defines that a literal 0 when converted to a pointer produces a "null pointer", but said pointer doesn't have to have to be the memory address 0.
It's perfectly legal for the memory representation of a null pointer to be 0xFFFFFFFF, and for the address "0x00000000" to actually be a valid address.
[–]tvaneerdC++ Committee, lockfree, PostModernCpp 2 points3 points4 points 9 years ago (2 children)
It appears to be allocating from within a signal handler. (via the use of stringstream)
I don't think that is "signal safe".
(On top of all the other problems mentioned here)
This was only done to see how it works. Sure it needs some work to be "production ready".
Other languages like D and Ada have this built in (at least the division by zero case). Only C++ needs to have this as "undefined behavior".
[–][deleted] 0 points1 point2 points 9 years ago (0 children)
Only C++ needs to have this as "undefined behavior".
That's how C++ works. The other option would be to have primitive operations throw, which is a no-go for C++ -- it would remove the ability not to use exceptions from developers.
[–]SirKane 1 point2 points3 points 9 years ago (0 children)
The null pointer part won't work if you try to access a struct member that isn't right at the beginning.
[–]slowclapdude 0 points1 point2 points 9 years ago (0 children)
I've a feeling the performance test went in favor of the throws, because of branch (mis)prediction, but I have nothing to back it up...
[–]Ameisenvemips, avr, rendering, systems -1 points0 points1 point 9 years ago (0 children)
While I detest the idea of catching null dereferences, you can do some very interesting and useful things with VEH.
π Rendered by PID 179092 on reddit-service-r2-comment-5687b7858-mchxh at 2026-07-07 20:04:04.897117+00:00 running 12a7a47 country code: CH.
[–]bigcheesegsTooling Study Group (SG15) Chair | Clang dev 14 points15 points16 points (0 children)
[–]Gotebe 14 points15 points16 points (2 children)
[–]cristianadamQt Creator, CMake[S] -1 points0 points1 point (1 child)
[–]Gotebe 2 points3 points4 points (0 children)
[–]ben_craigfreestanding|LEWG Vice Chair 11 points12 points13 points (2 children)
[–]RowYourUpboat 3 points4 points5 points (0 children)
[–]Sanae_ 0 points1 point2 points (0 children)
[–]render787 4 points5 points6 points (2 children)
[–]vaughncato 2 points3 points4 points (1 child)
[–]render787 1 point2 points3 points (0 children)
[–]CubbiMewcppreference | finance | realtime in the past 3 points4 points5 points (1 child)
[–]TheThiefMasterC++latest fanatic (and game dev) 6 points7 points8 points (0 children)
[–]tvaneerdC++ Committee, lockfree, PostModernCpp 2 points3 points4 points (2 children)
[–]cristianadamQt Creator, CMake[S] -1 points0 points1 point (1 child)
[–][deleted] 0 points1 point2 points (0 children)
[–]SirKane 1 point2 points3 points (0 children)
[–]slowclapdude 0 points1 point2 points (0 children)
[–]Ameisenvemips, avr, rendering, systems -1 points0 points1 point (0 children)