8

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.

Lonewolf
  • 497
  • 5
  • 13

1 Answers1

8

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_) {}
}
songyuanyao
  • 169,198
  • 16
  • 310
  • 405