What I don’t understand about C/C++ is:
Yes, everyone uses it to get blazingly fast executables, so they compile with optimization turned on.
But for compilation with debug information turned on, we don’t care about speed. So why not include more information in that compile mode, for example detect some segfaults before they happen? Effectively, insert an assert(ptr != NULL) before every access to a pointer ptr. Why can’t the compiler do that? Again, that should be off by default, but there should be such a possibility, I think.
EDIT: Some people said that the detection I suggested doesn’t make sense or doesn’t do anything that the report of segmentation fault wouldn’t already do. But what I have in mind is just a more graceful and informative abort, which prints the file name and line number of the offending code, just like an assert() would do.
There are a few major problems with your suggestion:
What conditions do you want the compiler to detect? On Linux/x86, unaligned access can cause
SIGBUSand stack overflow can causeSIGSEGV, but in both cases it technically is possible to write the application to detect those conditions and fail ‘gracefully’.NULLpointer checks can be detected, but the most insidious bugs are due to invalid pointer access, rather thanNULLpointers.The C and C++ programming languages provide enough flexibility so it is impossible for a runtime to determine with 100% success if a given random address is a valid pointer of an arbitrary type.
What would you like the runtime environment to do when it detects this situation? It can’t correct the behavior (unless you believe in magic). It can only continue executing or exit. But wait a minute… that’s what already happens when a signal is delivered! The program exits, a core dump is generated, and that core dump can be used by application developers to determine the state of the program when it crashed.
What you’re advocating actually sounds like you want to run your application in a debugger (
gdb) or through some form of virtualization (valgrind). This is already possible, but it makes no sense to do it by default, because it provides no benefit to non-developers.Update to respond to comments:
There’s no reason to modify the compilation process for debug versions. If you need a ‘gentle’ debug version of the application, you should run it inside of a debugger. It’s very easy to wrap your executable in a script that does this for you transparently.