使用指针和参考时发生非法指令
void writeFromNonRT(const T& data)
{
// get lock
lock();
// copy data into non-realtime buffer
*non_realtime_data_ = data;
new_data_available_ = true;
// release lock
mutex_.unlock();
}
要确定,我尝试编码类似的代码,例如:
#include <iostream>
using namespace std;
void pt_ref(int& data)
{
int *ptr;
ptr = &data; // ptr points to "data"
cout << "data's addres: "<< ptr <<"\n"; // print address
}
int main()
{
int x = 3;
pt_ref(x);
cout << "x's address: " << &x;
}
\\ output:
\\ data's addres: 0x7ffe05c17c4c
\\ x's address: 0x7ffe05c17c4c
此代码运行良好,但它与源代码仍然不同。
// these 2 lines are different.
*non_realtime_data_ = data;
ptr = &data;
因此,我尝试将ptr =&amp; data;
更改为*ptr = data;
,然后再次运行代码,发生了错误(“非法指令”)。
希望有人可以回答我,非常感谢。
PS:我在REPLIT在线编译器上运行了代码。
when reading the source codes of realtime_tools::RealtimeBuffer, I got lots of questions about the pointer and reference. The related codes are shown below:
void writeFromNonRT(const T& data)
{
// get lock
lock();
// copy data into non-realtime buffer
*non_realtime_data_ = data;
new_data_available_ = true;
// release lock
mutex_.unlock();
}
To figure out, I tried to code the similar code like:
#include <iostream>
using namespace std;
void pt_ref(int& data)
{
int *ptr;
ptr = &data; // ptr points to "data"
cout << "data's addres: "<< ptr <<"\n"; // print address
}
int main()
{
int x = 3;
pt_ref(x);
cout << "x's address: " << &x;
}
\\ output:
\\ data's addres: 0x7ffe05c17c4c
\\ x's address: 0x7ffe05c17c4c
This code runs well, but it's still different to the source code.
// these 2 lines are different.
*non_realtime_data_ = data;
ptr = &data;
So I tried to change ptr = &data;
to *ptr = data;
, and ran again the code, the error("illegal instruction") occurred.
Hope someone can answer me, thanks a lot.
PS: I ran the code on the replit online compiler.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是指针
ptr
是 (并且不指向任何int
对象)等在左侧删除该指针(您在**ptr
上写的指针)会导致不确定的行为。要解决此问题,请确保在取消
ptr
之前,指针ptr
指向某些int
对象。The problem is that the the pointer
ptr
was uninitialized(and does not point to anyint
object) and so dereferencing that pointer(which you did when you wrote*ptr
on the left hand side) leads to undefined behavior.To solve this make sure that before dereferencing
ptr
, the pointerptr
points to someint
object.