成功的取消引用似乎会导致潜在的段错误
Successful dereference seems to cause a latent segfault
如标题中所述,我成功取消引用了来自 modMYSTRUCT 和 showMeThis 函数的数据。显示“第四次检查”之前的正确输出,但出现段错误:
First check
Second check
0
Third check
Segmentation fault (core dumped)
但是,当我从(cout << "First check\n";
到 cout << "Third check\n";
)或(MYSTRUCT struct_inst;
到 cout << "Fourth check\n";
)发表评论时,这不会发生。当我这样做时,代码会为未注释的代码生成预期的输出。
产生段错误的上述代码:
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";
}
我在这里一无所知。对于上下文,我一直在寻找一种更好的方法来取消引用 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)
};
但老实说,仅仅因为您可以做到这一点,并不意味着您应该这样做。 :)
如标题中所述,我成功取消引用了来自 modMYSTRUCT 和 showMeThis 函数的数据。显示“第四次检查”之前的正确输出,但出现段错误:
First check
Second check
0
Third check
Segmentation fault (core dumped)
但是,当我从(cout << "First check\n";
到 cout << "Third check\n";
)或(MYSTRUCT struct_inst;
到 cout << "Fourth check\n";
)发表评论时,这不会发生。当我这样做时,代码会为未注释的代码生成预期的输出。
产生段错误的上述代码:
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";
}
我在这里一无所知。对于上下文,我一直在寻找一种更好的方法来取消引用 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)
};
但老实说,仅仅因为您可以做到这一点,并不意味着您应该这样做。 :)