0

I am getting a segmentation fault when running the following code. I know there is something fundamental I'm misunderstanding about pointers here, but I can't seem to figure it out.

#include <iostream>
using namespace std;

struct intptr{
  intptr* a;
  int value;
};

void printint(intptr q){
  if (q.a == &q){
    cout<<q.value<<endl;
    return;
  }
  else
    printint(*(q.a));
}

int main(){
  intptr y,z;
  z.value = 1;
  y.value = 2;
  *(y.a) = z;
  *(z.a) = z;
  printint(x);
}

I've also tried the following, but it never recognizes that q.a = &q is true.

#include <iostream>
using namespace std;

struct intptr{
  intptr* a;
  int value;
};

void printint(intptr q){
  if (q.a == &q){
    cout<<q.value<<endl;
    return;
  }
  else
    cout<<"not finished"<<endl;
    printint(*(q.a));
}

int main(){
  intptr y,z;
  z.value = 1;
  y.value = 2;
  y.a = &z;
  z.a = &z;
  printint(y);
}
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Matt Pennington
  • 560
  • 1
  • 8
  • 21
  • In your first example, you declare the pointer `intptr* a` in the struct but never give it a valid address (i.e., never allocate an address for it). So it points to an undefined location, and `*(q.a) = z` will crash. In both cases, `q` is a parameter on the stack of the function, so its address won't match the pointer variable, `a`. – lurker Feb 26 '14 at 02:57
  • changing the function declaration to accept a parameter passed by reference solved the problem. -- void printint(intptr &q) – Matt Pennington Feb 26 '14 at 03:01

3 Answers3

3

Here is your problem:

  *(y.a) = z;
  *(z.a) = z;

You are dereferencing a null pointer. The a variable was never initialized and points to nothing. If you are going to be using pointers, I strongly recommend following the rule of 3.

Community
  • 1
  • 1
yizzlez
  • 8,757
  • 4
  • 29
  • 44
0

To find the issue and avoid similar issues in future, it is recommended to initialized pointers to NULL and later check for NULL before operating them. I recommend you to add a constructor to your struct and initialize pointer a:

struct intptr
{
   intptr* a;
   int value;

   intptr()
   : a(NULL)
   { }
};
Evgeny Sobolev
  • 515
  • 4
  • 13
0

The problem has been pointed by @awesomeyi

Try the following codes:

  y.a = &z;
  z.a = &y;
Steve
  • 1,448
  • 11
  • 18