Search code examples
c++arraysstructsegmentation-faultdereference

Successful dereference seems to cause a latent segfault


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 check\n"; to cout << "Third check\n"; ) or from ( MYSTRUCT struct_inst; to cout << "Fourth check\n"; ). 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 check\n";
  int x[1][1] = { {0} };
  cout << "Second check\n";
  cout << showMeThis(&(**x)) << endl;
  cout << "Third check\n";


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

  cout << *(struct_inst.num) << endl;
  cout << "Fourth check\n";
}

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


Solution

  • 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. :)