[prog] C programming - capturing information sent to stdout

Kathryn Hogg kjh at flyballdogs.com
Thu Jul 14 12:40:44 EST 2005


Sue Stones said:
> Yes but I am asking where the boundaries of that expectation are.

In general, I use it for conditions that absolutely *must* be true.  Let's
say a write a function that takes a pointer as an argument and in the
documentation I've stated that the pointer must not be null.  In case, its
perfectly valid for me to put an assertion in place to check for this.

If I absolutely need to know the call chain where a condition is not met,
the core dump produced by an assert() failing, will allow me to examine
the call stack, etc after the fact.  I often do this when debugging nasty
problems on production machines at customer sites.

> At
> one level you could say that if you know enough to put a assert
> statement in there then you are expecting an error, so assert shouldn't
> be used.  Using assert to determine if preconditions have been met, says
> that you expect that some programmers will not comply with the
> preconditions, so assert shouldn't be met.

I could write my function so that if it passes in a NULL pointer then I
return some sort of error condition.  But then I have to trust the user of
the function to check the return value.

I tend to use assert() very frequently in private secondary functions and
do more robust error checking in the interface functions (the ones that
are part of the public API and others will call.

In C/C++ an assertion failure gives you very terse output:

    assert(ptr != 0);

will print something like
Assertion failed:   ptr != 0 at file xxxx.cc line nnn


>
> If a program is invisibly using a file or opening a pipe, which side of
> the border does this fall on?

In the case of opening a file, I generally want to know why it failed so
I'll print an error message including sterror()

   cout << "failed to open file " << filename << ": " << strerror(errno)
        << endl;

   and if I can't proceed with that, I'll call exit() or abort()

> My question is when the desired outcome of a failure to open a file *is
> to crash the program* is assert the right way to do this, or are these
> problems common enough that they need to be crashed explicitly?

assert is a quick way to put some sanity checks in place without having to
write alot of code.  These are things that you never, ever expect to be
false.


-- 
Kathryn
http://womensfooty.com



More information about the Programming mailing list