-4
 #include <stdio.h>

 struct p
 {
   int x[2];
 };

 struct q
 {
   int *x;
 };

 int main()
 {
   struct p p1 = {1, 2};
   struct q *ptr1;
   ptr1->x = (struct q*)&p1.x;
   printf("%d\n", ptr1->x[1]);
 }

I am not getting output of this code and segmentation fault is occurred. Which line is wrong in this the code or whole code is wrong?

ValLeNain
  • 2,232
  • 1
  • 18
  • 37
  • 6
    Because you have not allocated memory for `ptr1`. – Jiahao Cai Oct 27 '17 at 17:13
  • 2
    not quite sure you can build a `struct p` the way you do. You have to assign the int values to its `x` property. – ValLeNain Oct 27 '17 at 17:15
  • @OldProgrammer He's asking about why it happens and not what is that. – Michi Oct 27 '17 at 17:25
  • @OldProgrammer exactly I want to know why is that happening in my code? I know what is code dump and segmentation fault . – Shriram Jadhav Oct 27 '17 at 17:29
  • the posted code does not cleanly compile. The compiler outputs 3 messages (warnings). In the process of fixing those warnings, you should have also fixed the runtime problem. Hint: the pointer `ptr1` is not pointing to any memory owned by the application. Instead is is using what every trash was on the stack at the location of `ptr1` and trying to write to that random memory – user3629249 Oct 27 '17 at 17:29
  • `ptr1->x = (struct q*)&p1.x;` Even if you do that cast you still have an incompatible pointer – Michi Oct 27 '17 at 17:34
  • 1
    Please turn on all the compiler Warnings. This shouldn't compile. – Ajay Brahmakshatriya Oct 27 '17 at 19:30

2 Answers2

2
struct q *ptr1;
ptr1->x = (struct q*)&p1.x;

Pointer ptr1 is created, but is never initialized. The second line attempts to dereference the pointer. Since the pointer was never initialized and contains garbage, the second line is dereferencing an invalid memory address. You need to allocate a struct q and make ptr1 point to it before you can execute that second line.

bta
  • 43,959
  • 6
  • 69
  • 99
  • Apart from that there is type mismatch when assigning a `struct q*` to an `int*`. Also it is unclear what OP is trying to achieve by casting `&p1.x` – Ajay Brahmakshatriya Oct 27 '17 at 19:32
0

The guys here already pointed out, but just for putting that in actual sample code:

int main()
{
  struct p p1 = {1, 2};
  struct q q1;                  // reserve memory on stack
  struct q *ptr1 = &q1;         // let ptr1 point to it
  ptr1->x = (struct q*)&p1.x;   // cleaner: q1.x = p1.x; both are pointer to int
  printf("%d\n", ptr1->x[1]);
}

I'm not to a 100% sure whether p1 = {1, 2} shouldn't be rather p1 = { {1, 2} }, because the former one could be also used for e.g.

struct {
  int a;
  int b;
} P1 = {1, 2};
qdbp
  • 109
  • 1
  • 1
  • 12