My concern about this example:

void do_something(foo *p)
    if (p)

Is that by skipping the operation when the pointer is null is that it's not
clear what it should do if it's precondition isn't met.  Sure, it won't
crash, but it's also not going to "do something."  This can lead to corrupt
state and postpones discovery of the bug.

If do_something is a public API, then, yes, you have to decide, document,
and implement what to do if the caller passes in a null pointer.  If it's
an internal API, then the silent elision of the crash merely hides the bug
possibly corrupts the debugger's state.  A corrupt debugging state seems
(to me) at least as bad as an obvious crash to the user.  Crashes are going
to get complained about and investigated.  Silently doing the wrong thing
just wastes everyone's time.

On Tue, Sep 20, 2016 at 1:59 PM, Zachary Turner via lldb-dev <> wrote:

> On Tue, Sep 20, 2016 at 1:55 PM Greg Clayton <> wrote:
>> > On Sep 20, 2016, at 1:45 PM, Zachary Turner <> wrote:
>> >
>> > I do agree that asserts are sometimes used improperly.  But who's to
>> say that the bug was the assert, and not the surrounding code?  For
>> example, consider this code:
>> >
>> > assert(p);
>> > int x = *p;
>> Should be written as:
>> assert(p);
>> if (!p)
>>     do_something_correct();
>> else
>>     int x = *p;
>> >
>> > Should this assert also not be here in library code?  I mean it's
>> obvious that the program is about to crash if p is invalid.  Asserts should
>> mean "you're about to invoke undefined behavior", and a crash is *better*
>> than undefined behavior.  It surfaces the problem so that you can't let it
>> slip under the radar, and it also alerts you to the point that the UB is
>> invoked, rather than later.
>> >
>> > What about this assert?
>> >
>> > assert(ptr);
>> > int x = strlen(ptr);
>> >
>> > Surely that assert is ok right?  Do we need to check whether ptr is
>> valid EVERY SINGLE TIME we invoke strlen, or any other function for that
>> matter?  The code would be a disastrous mess.
>> Again, check before you call if this is in a shared library! What is so
>> hard about that? It is called software that doesn't crash.
>> assert(ptr)
>> int x = ptr ? strlen(ptr) : 0;
> I find it hard to believe that you are arguing that you cannot EVER know
> ANYTHING about the state of your program.  :-/
> This is like arguing that you should run a full heap integrity check every
> time you perform a memory write, just to be sure you aren't about to crash.
> If you make a std::vector<>, do we need to verify that its internal
> pointer is not null before we write to it?   Probably not, right?  Why
> not?  Because it has a specification of how it works, and it is documented
> that you can construct one, you can use it.
> It's ok to document how functions work, and it is ok to assume that
> functions work the way they claim to work.
> _______________________________________________
> lldb-dev mailing list
lldb-dev mailing list

Reply via email to