home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.std.c
- Path: sparky!uunet!taumet!steve
- From: steve@taumet.com (Steve Clamage)
- Subject: Re: Struct hack one last time (one last time)
- Message-ID: <1993Jan1.173852.26630@taumet.com>
- Organization: TauMetric Corporation
- References: <1992Dec31.153931.7495@hubcap.clemson.edu>
- Date: Fri, 1 Jan 1993 17:38:52 GMT
- Lines: 44
-
- mjs@hubcap.clemson.edu (M. J. Saltzman) writes:
-
- >In a previous article (now expired at my site), I asked if the
- >notorious "struct hack" was still conformant if the tail array in the
- >struct was of type other than char. Since no-one ever replied, I'll
- >ask one more time.
-
- >My reading of the earlier thread on this topic was that the hack was
- >indeed legal, but all the previous examples used an array of char in
- >their examples. Thus, is there any reason it would not be legal to
- >declare:
-
- > struct vector {
- > int size;
- > double v[1];
- > } *vec;
-
- >and then code (for example):
-
- > vec = malloc(sizeof(struct vector) + (n - 1) * sizeof(double));
- > vec->size = n;
-
- > for ( i = 0; i < vec->size; i++ ) vec->v[i] = 0.0;
-
- I don't see that the type of the array makes any difference.
-
- I do believe that the hack is not strictly conforming, however, since
- you would be using array indices outside the declared array bounds
- (char or double makes no difference). The results of doing so are
- undefined. Nonetheless, I don't know of any implementations where this
- would not work.
-
- I have thought of a plausible implementation where the struct hack
- would fail, however.
-
- An implementation is allowed to add padding to the end of a struct.
- Suppose that the implementation adds space to the end of each struct
- type where it encodes information used for run-time error checking.
- The struct hack would fail in this case, since it would overwrite data
- used by the run-time system. I believe the implementation would still
- be conforming, since we are in the arena of undefined behavior.
- --
-
- Steve Clamage, TauMetric Corp, steve@taumet.com
-