home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #31 / NN_1992_31.iso / spool / comp / std / c / 3312 < prev    next >
Encoding:
Text File  |  1993-01-01  |  1.9 KB  |  55 lines

  1. Newsgroups: comp.std.c
  2. Path: sparky!uunet!taumet!steve
  3. From: steve@taumet.com (Steve Clamage)
  4. Subject: Re: Struct hack one last time (one last time)
  5. Message-ID: <1993Jan1.173852.26630@taumet.com>
  6. Organization: TauMetric Corporation
  7. References: <1992Dec31.153931.7495@hubcap.clemson.edu>
  8. Date: Fri, 1 Jan 1993 17:38:52 GMT
  9. Lines: 44
  10.  
  11. mjs@hubcap.clemson.edu (M. J. Saltzman) writes:
  12.  
  13. >In a previous article (now expired at my site), I asked if the
  14. >notorious "struct hack" was still conformant if the tail array in the
  15. >struct was of type other than char.  Since no-one ever replied, I'll
  16. >ask one more time.
  17.  
  18. >My reading of the earlier thread on this topic was that the hack was
  19. >indeed legal, but all the previous examples used an array of char in
  20. >their examples.  Thus, is there any reason it would not be legal to 
  21. >declare:
  22.  
  23. >    struct vector {
  24. >        int  size;
  25. >        double v[1];
  26. >    } *vec;
  27.  
  28. >and then code (for example):
  29.  
  30. >    vec = malloc(sizeof(struct vector) + (n - 1) * sizeof(double));
  31. >    vec->size = n;
  32.  
  33. >    for ( i = 0;  i < vec->size;  i++ )  vec->v[i] = 0.0;
  34.  
  35. I don't see that the type of the array makes any difference.
  36.  
  37. I do believe that the hack is not strictly conforming, however, since
  38. you would be using array indices outside the declared array bounds
  39. (char or double makes no difference).  The results of doing so are
  40. undefined.  Nonetheless, I don't know of any implementations where this
  41. would not work.
  42.  
  43. I have thought of a plausible implementation where the struct hack
  44. would fail, however.
  45.  
  46. An implementation is allowed to add padding to the end of a struct.
  47. Suppose that the implementation adds space to the end of each struct
  48. type where it encodes information used for run-time error checking.
  49. The struct hack would fail in this case, since it would overwrite data
  50. used by the run-time system.  I believe the implementation would still
  51. be conforming, since we are in the arena of undefined behavior.
  52. -- 
  53.  
  54. Steve Clamage, TauMetric Corp, steve@taumet.com
  55.