Re: Bug analysis
- From: blargg.h4g@xxxxxxxxxxxxx (blargg)
- Date: Mon, 12 Jan 2009 08:25:48 -0600
jacob navia wrote:
C unleashed page 266, Listing 8.2[...]
---------------------------------
char *ReadTextFile(FILE *fp,int *Error)
{
size_t size=0;
size_t len;
char *p = NULL;
char *q;
char buffer[120];
*Error = 0;
while (fgets(buffer, sizeof buffer, fp) {
len = strlen(buffer);
q = realloc(p,size+len);
if (q != NULL) {
p = q;
strcpy(p+size,buffer);
size += len;
}
else *Error = 1;
}
return p;
}
Note that if the realloc fails, the program will go on trying to
reallocate the buffer, what probably will always fail. This is
not really a bug, but it would have been obviously better to add
a "break" statement to stop reading after we can't reallocate.
As a user, I'd prefer a program say "out of memory" than hang
indefinitely.
But what if a given line is somewhat long, and the realloc for it
fails, but then the NEXT line is shorter and the realloc succeeds?
Then the concatenated data will be missing the line, though *Error
will have been set so the caller can still know of the problem.
Contrary to many people here, I find the postings of "Han from China"
very interesting.
And quite funny at times, as long as one isn't overly serious.
The writer of this code is an experienced C programmer. The fact that he
has this bug, that is a classical bug with zero terminated strings,
proves ONCE AGAIN that it is better to use counted strings where the
programmer has less bug surface.
For instance, in the implementation of the string library in lcc-win you
would write
String str = StrFromFile("text.dat",0); // Zero for text mode
and you would obtain a string, eliminating the need of all that code
above.
How is this an argument for any particular implementation of string?
Having a pre-packaged function that works helps no matter what is
being discussed, for sure.
What is "bug surface"?
It is the amount of details that the programmer must keep in mind when
using the libraries of the programming environment.
Boring details, lead to more bugs. Higher level functions lead to
less bugs.
And thus reuse is a prime tool for reducing bugs, and language
features fostering easier reuse are very desirable.
.
- References:
- Bug analysis
- From: jacob navia
- Bug analysis
- Prev by Date: Re: inline doesn't work - what I am doing wrong?
- Next by Date: inet_ntoa not returning correct values
- Previous by thread: Re: Bug analysis
- Next by thread: C vs. C++
- Index(es):
Relevant Pages
|