Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor reference parameter results in seg fault

Tags:

c++

ros

I am using the following code in a ROS application.

class RobotisController
{
private:
    ....
public:
    ros::NodeHandle pxxx;
}

RobotisController::RobotisController(ros::NodeHandle& nh) : pxxx(nh)
{
    packetHandlerList.push_back(PacketHandler::getPacketHandler(1.0));
    packetHandlerList.push_back(PacketHandler::getPacketHandler(2.0));
}


class RosWrapper {
protected:
    Robotis::RobotisController controller_;
    ros::NodeHandle nh_;
    ....

public:
    RosWrapper() :
            controller_(nh_) {}
}


main()  
{
    RosWrapper interface;
}

When I run the above code it leads to a SIGSEGV. I tried to debug the code and when I reach the constructor of the RobotisController, I find that the variable passed to the constructor nh shows cannot access memory, but the memory is already allocated in the class RosWrapper.

like image 534
Lonewolf Avatar asked Apr 20 '16 03:04

Lonewolf


1 Answers

The member variables will be initialized in order of declaration in the class definition. That means nh_ will be initialized after controller_. So pass an uninitialized nh_ as the argument to initialize controller_ will lead to UB.

You might change the order of declaration:

class RosWrapper {
protected:
    ros::NodeHandle nh_;  // nh_ will be initialized firstly
    Robotis::RobotisController controller_;
    ....

public:
    RosWrapper() :
            controller_(nh_) {}
}
like image 136
songyuanyao Avatar answered Oct 29 '22 18:10

songyuanyao