As far as possible:
union
discriminator should be checked before accessing
a field of the union
.
We have already seen, in previous sections, how the checks are made part of the accessors when the unions and arrays are members of a structure.
To enable us to enforce array bounds checking, whenever an array is passed to a function, we also pass the bounds of the array. (Alternatively, we pass enough information that the bounds of the array can be computed). For instance:
int
copy_int_stack(
int_stack stack,
int nels, /* max array size */
int els[]
)
{
int i;
i = 0;
while( !is_empty_int_stack(stack) ) {
assert(i < nels); /* bounds check */
els[i] = top_int_stack(stack);
i++;
pop_int_stack(stack);
}
return i;
}