1

I've just encountered a VERY weird thing:

I have a struct, say:

typedef struct {
int x;
} STRUCT;

[I know I can just say struct STRUCT without the typedef :)]

and a pointer STRUCT *p = NULL;

Suppose this pointer is (still) null at the time I execute this inside a function:

int *a = &p->x;

Why does this actually work? But this: int a = p->xgives a nullptr error?

EDIT: As far as I've read, the '->' operator has higher precedence than address-of (&).

PhantomR
  • 605
  • 4
  • 16
  • 1
    Probably undefined behaviour. – Oliver Charlesworth Dec 04 '17 at 16:28
  • 1
    Just because it compiles does *not* mean it is valid. – Jesper Juhl Dec 04 '17 at 16:30
  • @OliverCharlesworth but shouldn't p->x run first? – PhantomR Dec 04 '17 at 16:31
  • @JesperJuhl but it runs.. I added that only statement in main() and the program completes successfully. – PhantomR Dec 04 '17 at 16:32
  • @PhantomR that still doesn't mean anything. A program with undefined behaviour may well compile and run. You just can't be sure what it will actually do. And what it does for you it may not do for someone else who builds it with a slightly different compiler or on a different platform. It is *your responsibility* to not write undefined behaviour. The compiler is not obliged to diagnose it for you always - it'll just generate "something". – Jesper Juhl Dec 04 '17 at 16:36
  • @PhantomR -- C++ doesn't work this way, where if you knowingly do things wrong, the program will crash. Think of it this way -- if you had your driver's license revoked, that doesn't stop you from getting into a car and driving it, even though it would be illegal. – PaulMcKenzie Dec 04 '17 at 16:36
  • That's quite strange, but thank you all for your help. It's actually not my code, but I read a line similar to the one I said and noticed it actually worked without any error. – PhantomR Dec 04 '17 at 16:39
  • 1
    This is one of these UB errors that works in pretty much any compiler, because the expression is translated to `int *a = (int*)(&p)` (the standard requires `p` to be equal to the pointer to the initial member). – Sergey Kalinichenko Dec 04 '17 at 16:44
  • Thank you everyone for your help. – PhantomR Dec 09 '17 at 13:21

0 Answers0