Richard said:
I've got this:
typdef struct
{
int x;
int y;
} Point;
// I now want to make a function that checks if a Point is empty
Based on your later articles I see that you really want to check
whether Point is uninitialized. Well, there's no fail-safe way
to do that, but you can do pretty well by adding a "checksum"
member to the struct, like this:
typedef struct {
int x;
int y;
int checksum;
} Point;
The `checksum' value should depend on `x' and `y' using some kind
of fixed formula, e.g. `checksum = x + y + 555;' The exact
formula isn't too important, but there are a couple of
considerations to keep in mind. First, it should be difficult
for `checksum' to be accidentally correct. That means that, for
example, the case of (x, y, checksum) = (0, 0, 0) should *not* be
valid, and the same goes for other cases where the entire
structure is filled with a single byte value. (This is the
reason for the addition of 555 in my suggested formula.
Otherwise (0, 0, 0) would be valid.) I'm sure you can think of
some other considerations.
Then, whenever you update a Point, update the `checksum' member
as well. Whenever you examine a Point, verify that `checksum' is
correct. When you free a Point, zero `checksum'.
This technique is not entirely fail-safe, of course. First, if
you free a Point without clearing the checksum[*], and then reuse
the same memory later without reinitializing it, it will check
out okay. Second, use of uninitialized values technically
provokes undefined behavior in C. You could get around that by
treating Point and `checksum' as unsigned char arrays, but it's
probably not worth it.
[*] I don't necessary mean via the free() function. There are
other ways to allocate and free objects.