0

Possible Duplicate:
Why does this C code work?

Why doesn't this code for finding the offset of a field in a struct give segfault ?

#define offset(structName,fieldName) (&((structName *)0)->fieldName)
Community
  • 1
  • 1
  • 4
    Funny, usually people ask why their code _does_ give segfault... – SingerOfTheFall Aug 06 '12 at 09:26
  • It might; technically, it's undefined behavior. But most compilers will optimize this to a constant number, so in those, this can be used as the implementation of offsetof(). In general, offsetof() implementation is left up to the compiler; gcc does indeed use __builtin_offsetof(). – Ambroz Bizjak Aug 06 '12 at 09:30
  • Wikipedia page on offsetof gives some clues: http://en.wikipedia.org/wiki/Offsetof – Ambroz Bizjak Aug 06 '12 at 09:31
  • 1
    And the library delivered with the compiler can do things like this, because the library knows exactly what the compiler will do with it. As a programmer, you shouldn't (unless you don't care about portability and the compiler explicitly guarantees it). – James Kanze Aug 06 '12 at 09:32
  • 1
    Undefined behavior doesn't mean "this will crash". It means the behavior is undefined. – Keith Thompson Aug 06 '12 at 09:40

1 Answers1

3

Because it is not accessing any data. It's just computing an address. Try doing either of these operations:

foo = *offset(MyStruct, MyField);
*offset(MyStruct, MyField) = 1234;

And you'll see a beautiful SEGFAULT :-)

Claudi
  • 5,224
  • 17
  • 30