There are several remarks that can be done about our program. The first one is that the memory allocator could very well fail, when there is no more memory available. When the allocator fails, it returns NULL. Since we never test for this possibility, our program would crash in low memory 858e46i conditions. What a shame!
We arrange for this immediately. Instead of using the allocator, we will write a function that will call the allocator, test the result, and call the exit() routine if there is no more memory left. Continuing processing without more memory is impossible anyway.
void *xmalloc(unsigned int size)
return result;
Note that we keep the same signature, i.e. the same type of result and the same type of arguments as the original function we want to replace. This is function sub classing.
Note too, that we use fprintf instead of printf. Fprintf takes an extra argument, a file where the output should go. We use the predefined file of standard error, instead of the normal output file stdout, that printf implicitly takes.
Why?
Because it is possible that the user redirects the output to a file instead of letting the output go directly to the screen. In that case we would write our error messages to that file, and the user would not see the error message.
We change all occurrences of malloc by xmalloc, and this error is gone.
We change too, all other error-reporting functions, to take into account stderr.
But there are other issues. Take for instance our finddata_t structure that we carry around in each STREAM structure. What's its use? We do not use it anywhere; just copy it into our STREAM.
But why we introduced that in the first place?
Well, we didn't really know much about findfirst, etc, and we thought it could be useful.
So we are stuck with it?
No, not really. Actually, it is very easy to get rid of it. We just change the structure STREAM like this:
typedef struct tagStream STREAM;
and we take care to erase any references to that member. We eliminate the memcpy calls, and that's all. Our program is smaller, uses less memory, and, what is essential, does the same thing quicker than the older version, since we spare the copying.
It is very important to learn from the beginning that software gains not only with the lines of code that you write, but also with the lines of code that you eliminate!
|