Run-time Checks for C
Chris Torek
chris at mimsy.UUCP
Mon Nov 21 09:44:51 AEST 1988
In article <566 at mks.UUCP> tj at mks.UUCP (T. J. Thompson) writes:
>Consider the following semi-realistic code fragment:
(replaced with a simpler version:)
struct string {
int hashval;
char str[1];
};
struct string *
intern(char *s) {
struct string *sp;
/* assuming dpANS-conformant malloc() */
if ((sp = malloc(sizeof(*sp) + strlen(s))) != NULL) {
sp->hashval = hash(s);
(void) strcpy(sp->str, s);
}
return (sp);
}
>I suggest that no amount of cleverness on the part of the compiler and malloc
>can limit a pointer derived from np->v.n.name to the precisely correct range
>(np->v.n.name[0] .. np->v.n.name[strlen(name)]).
[here sp->str[0] .. sp->str[strlen(name)]
The compiler *can* check this, in either of two ways: It can limit you to
sp->str[0]..sp->str[0]:
>The compiler could limit any pointer derived from np->v.n.name to that value
>only, based on the length of the array in the type declaration. This would
>cause the strcpy to fail (and would probably break 98% of existing programs).
I think this estimate is rather high. It would break some programs.
>The pointer derived from np->v.n.name could be limited to the object returned
>by malloc (i.e. the limits on np->v.n.name could be inherited from np).
>This would permit np->v.n.name[-1]=0; clearly wrong.
This is, I think, what existing checking-compilers do. It is not perfect,
but it works.
>There could be a special arrangement to allow the relaxation of limits on
>a trailing array member of an aggregate ...
This would work without reservation provided the relaxation applies only
to objects allocated with malloc.
--
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain: chris at mimsy.umd.edu Path: uunet!mimsy!chris
More information about the Comp.lang.c
mailing list