Re: Debugging standard C library routines
- From: Eric Sosman <esosman@xxxxxxxxxxxxxxxxxxx>
- Date: Sun, 01 Oct 2006 13:01:55 -0400
jacob navia wrote:
Frederick Gotham wrote:
Richard Heathfield posted:
>
Initialise every pointer.
Initializing every pointer does no harm, [...]
It does no harm to the running program, certainly. But
it *does* harm the process of developing the program, by
removing the compiler's ability to warn about certain kinds
of errors. Example:
char *next_field(char **start)
{
char *p /* = NULL */, *q /* = NULL */;
/* Skip white space to find the start of the field: */
p = *start + strspn(*start, " \t\f\r\n");
/* Skip non-whites to find the end of the field: */
p = p + strcspn(p, " \t\f\r\n");
/* Record where the next search should start: */
*start = q + (*q != '\0');
/* Zero-terminate the field just located: */
*q = '\0';
/* Return a pointer to its beginning: */
return p;
}
.... is an erroneous attempt to locate and snip a white-space-
delimited field from a string. The error is in the second
assignment: The result of the expression involving strcspn()
ought to have been assigned to q, not to p (we want p to point
to the start of the field, q to point just past its end). If
q is not initialized at the point of declaration, many compilers
will warn about its use in the third assignment: they will see
that it is being read without having been given a value and will
squawk about it. But if the declaration of q also initializes it,
the compiler won't complain about using a variable that may not
have been initialized, and the error may go undetected longer.
The cheapest errors are those not made in the first place.
The next-cheapest are those caught by the compiler and fixed
before committing the code. Errors that actually make it as far
as a testing phase -- or into deployment, may the Lord have mercy
on us! -- are more expensive than those caught earlier, so it is
a good idea to give the compiler every encouragement to catch
errors early. Wanton initialization of pointers (of any variables,
actually) discourages the compiler's assistance and therefore ought
not to be indulged in.
--
Eric Sosman
esosman@xxxxxxxxxxxxxxxxxxx
.
- Follow-Ups:
- Re: Debugging standard C library routines
- From: Richard Heathfield
- Re: Debugging standard C library routines
- References:
- Debugging standard C library routines
- From: achintmehta
- Re: Debugging standard C library routines
- From: Richard Heathfield
- Re: Debugging standard C library routines
- From: Frederick Gotham
- Re: Debugging standard C library routines
- From: jacob navia
- Debugging standard C library routines
- Prev by Date: Re: Debugging standard C library routines
- Next by Date: Re: Malloc and free questions - learner questions
- Previous by thread: Re: Debugging standard C library routines
- Next by thread: Re: Debugging standard C library routines
- Index(es):
Relevant Pages
|