Assert and undefined behavior

rikki cattermole rikki at cattermole.co.nz
Wed Oct 11 09:38:58 UTC 2017


On 11/10/2017 10:27 AM, John Burton wrote:
> The spec says this :-
> 
> "As a contract, an assert represents a guarantee that the code must 
> uphold. Any failure of this expression represents a logic error in the 
> code that must be fixed in the source code. A program for which the 
> assert contract is false is, by definition, invalid, and therefore has 
> undefined behaviour."
> 
> Now I worry about the words "undefined behavior" because in C++ compiler 
> writers seem to have decided that these words mean that it's ok for the 
> compiler to generate code to do whatever it feels like even in 
> unconnected code and even before the undefined behavior is invoked 
> because some subsequent code has undefined behavior.
> 
>  From my C++ experience this paragraph tells me that if I use "assert" 
> to check my assumptions, and the assertion is false, then this could 
> lead to my program failing in unpredictable ways unconnected with the 
> actual assertion.
> 
> I therefore feel like I ought to not use assert and should instead 
> validate my assumptions with an if statement and a throw or exit or 
> something.
> 
> I feel like a failing assertion should not cause "undefined behavior" in 
> the sense it is commonly used in C++ programming these days but should 
> have exactly defined behavior that it will do nothing if the assert 
> passes and throw the specified exception if it fails. Can I safely 
> assume this despite the wording?
> 
> I know this might seem like a small or pedantic point, but C++ compilers 
> can and do use invoking undefined behavior as an excuse to do all kinds 
> of unexpected things in generated code these days and I want to write 
> safe code :) I feel that if D is specified in the same way then assert 
> is not safe for me to use in a real program.

You misinterpreted it.

The program /could/ be in an invalid state because an internal state 
check (assert) says that it isn't.

What the compiler generates for the assert, depends upon the platform 
and if its building with optimizations. But all of them will end in the 
process crashing unless you go out of your way to handle it.

By default it throws and Error in debug mode, which you shouldn't be 
catching since it is an Error and not an Exception anyway.


More information about the Digitalmars-d-learn mailing list