next up previous contents
Next: CLW functions Up: Objective Previous: Objective   Contents

A typical example

Example 1 demonstrates a piece of code that would cause problems on exe cution. Whereas the code appears to be correct at first sight, it does hide a potential problem. If the file permissions of the file to be opened do not allow the program to open it for writing data, the program can (hopefully does) abort.
#include <stdio.h>

int main(int argc, char** argv)
{
    FILE* f;
    f = fopen("readonly", "w" );
    fprintf(f, "hello world\n");
    fclose(f);

    return 0;
}
This may lead to a segmentation violation, but it is not defined to do so. Therefore, the code is unpredictable and hence unsafe.

In example 2, the same code can be found, but now all (at least a lot) error checking is done.

#include <stdio.h>

int main(int argc, char** argv)
{
    FILE* f;
    f = fopen("readonly", "w" );
    if (errno != 0 )
    {
        reportError("Can't (f)open file: %i", errno);
    } else 
    { 
    }
    if (f) 
    {
        fprintf(f, "hello world\n");
        fclose(f);
        if (errno != 0) 
        {
            reportError("fclose");
        }
    } else
    {
        reportError("Can't write to NULL file");
    }
    return 0;
}
Example 2: This version is quite safe, but hard to read The program will not abort. But instead of three simple lines the code has become a complex set of 12 lines, with nested if-then-else constructs. And it becomes harder to follow the normal flow. This will make the code unsafe, especially after several maintenance updates have been done.

In example 3 the C Library Wrapper (CLW) is used. Again, the program is failsafe, but the readability is not decreased; it is still three lines of code. Some may even find it better understandable, as it becomes clear at first sight that the functions are safe.

#include <stdio.h>
#include <clw.h>

int main(int argc, char** argv)
{
    FILE* f;

    f = clw_fopen("readonly", "w" );
    clw_fprintf(f, "hello world\n");
    clw_fclose(f);

    return 0;
}
Example 3: This version is safe, easy to maintain and read.


next up previous contents
Next: CLW functions Up: Objective Previous: Objective   Contents
Erwin Nijmeijer 2002-09-26