home bbs files messages ]

Forums before death by AOL, social media and spammers... "We can't have nice things"

   comp.lang.c      Meh, in C you gotta define EVERYTHING      243,242 messages   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]

   Message 241,276 of 243,242   
   Keith Thompson to BGB   
   Re: Nice way of allocating flexible stru   
   09 Oct 25 19:50:43   
   
   From: Keith.S.Thompson+u@gmail.com   
      
   BGB  writes:   
   > On 10/8/2025 8:39 PM, Kaz Kylheku wrote:   
   >> On 2025-10-08, Keith Thompson  wrote:   
   >>> But in addition to that, in Kaz's example, n is not a constant   
   >>> expression, so `&(t.member-designator)` is not an address constant   
   >>> and therefore `offsetof(S, A[n])` has undefined behavior.   
   >> Great; I'd like to hear reasons to avoid it so I don't look foolish   
   >> for having overlooked it for manytyears. :)   
   >>   
   >>> Every compiler I've tried handles this "correctly", and I tend to   
   >> I'm sure I've seen foo.bar expressions on the right of an offsetof,   
   >> but those still yield constants.   
   >>   
   >   
   > I think it is a case of, it is not required to work...   
   >   
   > But, if the typical implementation is something like, say:   
   > #define offsetof(T, M)  ((long)(&(((T *)0)->M)))   
   >   
   > It is probably going to work without issue.   
      
   The cast needs to be (size_t), not (long).  With that change,   
   the behavior is still undefined, but it's likely to work in most   
   implementations, which is all that's required for code that's part   
   of the implementation.   
      
   Several implementations I've tried (gcc, clang, tcc) implement the   
   offsetof macro via "__builtin_offsetof".  Whatever compiler magic   
   is used to implement "__builtin_offsetof" typically works correctly   
   for Kaz's example (which is of course one of the possible results of   
   undefined behavior).  One other compiler I've tried has a #define   
   similar to yours (and also gets the type wrong, but the author of   
   that implementation is not interested in bug reports from me).   
      
   --   
   Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.com   
   void Void(void) { Void(); } /* The recursive call of the void */   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]


(c) 1994,  bbs@darkrealms.ca