[LCP]wrapper around strcmp

Greg Black gjb at gbch.net
Fri May 24 02:19:05 UTC 2002


"sasidhar p" wrote:

|   I am interested in a wrapper around 'strcmp' to avoid problems that might 
| occur when one of the agruments to 'strcmp' are NULL. I would like your 
| opinions/advice on the following two approaches in terms of efficiency as I 
| plan keep them in my library routines.
| 
| 1)  inline bool streq1(const char*a, const char*b) {
|       if (!a || !b || a[0] != b[0])
|         return false;
|       return !strcmp(a,b);
|     }
| 
| 2)  inline bool streq2(const char*a, const char*b) {
|       assert(a != NULL);
|       assert(b != NULL);
|       return !strcmp(a,b);
|     }

Both are absurd if you really mean to use them as library
functions: the first because it returns nonsensical results in
the face of a null pointer; the second because library functions
should not generally call abort() (which assert() does when the
assertion fails).

Number one is always absurd because it masks real errors and
allows your program to proceed even in the face of idiotic data
which could well cause later crashes or incorrect results.

Number two makes sense in the program itself and the approach of
using assert() liberally should be applied in all new code, at
least for the testing phases.  Once rigorous testing has been
completed, you can recompile the code with -DNDEBUG to remove
the assert() calls if you're sure that there are no more bugs[1]
and would prefer it not to make them clear if any have escaped
your attention.

In general, it's good to learn not to call library functions
such as strcmp() with null pointers and assert() is helpful in
weeding out such errors.

[1] Note that there is no such thing as a non-trivial program
    that can be guaranteed not to have bugs.

Greg




More information about the linuxCprogramming mailing list