使用指针和引用时发生非法指令

illegal instruction occur while using pointer and reference

阅读the source codes of realtime_tools::RealtimeBuffer时,我对指针和引用有很多疑问。相关代码如下:

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 = &data;更改为*ptr = data;,并再次运行代码,发生错误(“非法指令”)。

希望有人能回答我,非常感谢

PS: 我运行replit在线编译器上的代码

I tried to change ptr = &data; to *ptr = data;, and ran again the code, the error("illegal instruction") occurred.

问题是指针ptr未初始化(并且不指向任何int 对象),因此取消引用该指针(当你在左侧写 *ptr 时所做的)导致 未定义的行为

    int *ptr;   //pointer ptr does not point to any int object as of now    
   *ptr = data;
//-^^^^--------->undefined behavior since ptr doesn't point to any int object

要解决此问题,请确保在取消引用 ptr 之前,指针 ptr 指向某个 int 对象。

void pt_ref(int& data) 
{
    int var = 10; //int object
//-------------vvvv-------->now ptr points to "var"
    int *ptr = &var; 
//--vvvv------------------->this is fine now       
    *ptr = data;             
}