Successful dereference seems to cause a latent segfault

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error Successful dereference seems to cause a latent segfault on this date .

As mentioned in the title, I’m successfully dereferencing the data coming to and from the modMYSTRUCT and showMeThis functions. The proper output before “Fourth check” displays but a segfault occurs:

First check
Second check
0
Third check
Segmentation fault (core dumped)

This doesn’t happen, however, when I comment from ( cout << "First checkn"; to cout << "Third checkn"; ) or from ( MYSTRUCT struct_inst; to cout << "Fourth checkn"; ). When I do so, the code produces the expected output for the uncommented code.

The afformentioned code producing the segfault:

struct MYSTRUCT
{
  int * num;
};

void modMYSTRUCT( MYSTRUCT * struct_inst )
{
  cout << *(struct_inst->num) << endl;
  *(struct_inst->num) = 2;
}

int showMeThis( int * x )
{
  return *x;
}

int main()
{
  cout << "First checkn";
  int x[1][1] = { {0} };
  cout << "Second checkn";
  cout << showMeThis(&(**x)) << endl;
  cout << "Third checkn";


  MYSTRUCT struct_inst;
  *(struct_inst.num) = 1;
  modMYSTRUCT(&struct_inst);

  cout << *(struct_inst.num) << endl;
  cout << "Fourth checkn";
}

I’m clueless here. For context, I was looking for a better way to dereference GLM matrices. Any ideas?

Answer

Replace your MYSTRUCT with this:

struct MYSTRUCT
{
  int * num;                    
  MYSTRUCT() {num = new int;}   // allocate memory for an integer
  ~MYSTRUCT() {delete num;}     // free memory (will be called when struct_inst goes out of scope)
};

But honestly, just because you can do this, doesn’t mean you should. 🙂