6 Data protection with strong type checking

The scheme in section 5 works, but it is prone to a particular problem: there is no type checking. Because the pointers to all types are void pointers, it is easy to mistake one for another. The compiler cannot enforce any type checking, at all.

To fix this problem, we can introduce an empty structure type:

struct Complex
{
};

This type, struct Complex (upper case C) will be placed in complex.h, so it is visible to all users of the Complex type. In complex.c, we cast all pointers to struct Complex into pointers to struct complex (note the case change) before accessing the actual fields of a struct complex.

This works because implicit pointer casting generates a warning. In other words, a C compiler generates a warning from the following code:

struct Complex *ptr1;
struct X
{
};
struct X *ptr2;

// ...

ptr2 = ptr1;

It does mean that the programmer should read and fix all the compiler warnings, and not only the errors.



Copyright © 2006-08-28 by Tak Auyeung