-2

Given the following scenario :

typedef struct d
{
  int x;
} D;

typedef struct c
{
  D d;
} C;

typedef struct b
{
  struct c *c;
} B;

typedef struct a
{
  B b;
} A;

int main()
{
  A *p1;
  D *p2;

  p2 = &p1->b.c->d;
}

My question is : how it could be possible to have (p2 != NULL) IF (p1->b.c == NULL) ?

  • Where is anything set to `NULL`? All I see is an uninitialized `p1` used in the assignment to `p2`?? – David C. Rankin Mar 01 '20 at 10:37
  • Because dereferencing uninitialised and NULL pointers are undefined behaviour. That means the program may crash, or it may put `0` in `p2`, or it may put a non-zero value in `p2` or it can be any other undefined behaviour. – kaylum Mar 01 '20 at 10:37
  • `p2` has not been assign a value. You cannot dereference it. – pmg Mar 01 '20 at 10:39

1 Answers1

1

If you dereference (use) the pointer which does not reference any object is an Undefined Behaviour.

int main()
{
  A *p1;
  D *p2;

  p2 = &p1->b.c->d; // <- undefined behaviour anything can happen as p1 value is undetermined
}

What you should do is to initialize the variables first.

int main()
{
  A a1;
  B b1;
  C c1;
  D d1;
  A *p1 = &a1;
  D *p2;

  p1 -> b = b1;
  p1 -> b.c = &c1;
  p1 -> b.c -> d = d1;
  p2 = &p1 -> b.c -> d;
}

PS - there is not NULL pointer anywhere in your code. So actually I do not understand the question,

0___________
  • 60,014
  • 4
  • 34
  • 74