3 ms·
> Once the compiler encounters undefined behavior, it's free to do whatever it wants. like, produce an executable that does exit(0); when it hits that condition
by MaxBarraclough 6y ago
> Once the compiler encounters undefined behavior, it's free to do whatever it wants. like, produce an executable that does exit(0); when it hits that condition. Compiler writers are generally ethical people that won't do that
This is wrong on two points.
Firstly, real world compilers very often do handle various kinds of undefined behaviour with immediate termination. On many platforms, dereferencing a null pointer will result in a segfault. Sometimes compilers generate code to trap if undefined behaviour would result. In the C++ standard, some errors are defined to result in a call to std::terminate, rather than undefined behaviour. [0]
Secondly, as IgorPartola indicates, doing this isn't irresponsible, it's the least bad way to handle undefined behaviour. If your loop has overrun the end of your array, you generally don't want the execution to silently proceed with invalid data, you want execution to end immediately.
[0] https://stackoverflow.com/a/43675980/ https://stackoverflow.com/a/43675980/