Path: utzoo!utgpu!watmath!clyde!att!osu-cis!tut.cis.ohio-state.edu!mailrus!ncar!tank!mimsy!chris From: chris@mimsy.UUCP (Chris Torek) Newsgroups: comp.lang.c Subject: Re: Run-time Checks for C Message-ID: <14655@mimsy.UUCP> Date: 20 Nov 88 23:44:51 GMT References: <10113@umn-cs.CS.UMN.EDU> <566@mks.UUCP> Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742 Lines: 52 In article <566@mks.UUCP> tj@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@mimsy.umd.edu Path: uunet!mimsy!chris