c++pointersreferenceillegal-instruction

illegal instruction occur while using pointer and reference


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.


Solution

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

    The problem is that the the pointer ptr was uninitialized(and does not point to any int object) and so dereferencing that pointer(which you did when you wrote *ptr on the left hand side) leads to undefined behavior.

        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
    

    To solve this make sure that before dereferencing ptr, the pointer ptr points to some int object.

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