成功的取消引用似乎会导致潜在的segfault



如标题中所述,我成功地取消了进出modMYSTRUCTshowMeThis函数的数据引用。在">第四次检查";显示但发生分段故障:

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

然而,当我从(cout << "First checkn";cout << "Third checkn";(或从(MYSTRUCT struct_inst;cout << "Fourth checkn";(进行注释时,这种情况不会发生。当我这样做时,代码会为未注释的代码生成预期的输出。

产生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";
}

我在这里一无所知。就上下文而言,我正在寻找一种更好的方法来解引用GLM矩阵。有什么想法吗?

用以下内容替换MYSTRUCT

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)
};

但老实说,仅仅因为你能做到这一点,并不意味着你应该做到

最新更新