creating publisher in private nodehandle gives bad_alloc error

asked 2021-02-03 20:14:08 -0500

frpunzalan gravatar image

Hi everyone, I encountered a weird error while using a private ros::NodeHandle. It throws a bad_alloc error when I create a publisher. The code goes something like the following:

// In main

int main(int argc, char*argv[]) {
  ros::init(argc, argv, "my_class");

  ros::AsyncSpinner spinner(2);
  ros::NodeHandle node;
  ros::NodeHandle private_nh("~");

  auto app = std::make_shared<MyClass>(node, private_nh);

  if (!app->Init()) {
    return -1;
  if (!app->Spin()) {
    return -1;
  return 0;

// In MyClass

bool MyClass::Init() {
  // the following runs OK
  ros::Publisher chatter_pub = node.advertise<std_msgs::String>("chatter", 1000);

  // however, creating a publisher in private node handle throws an error
  ros::Publisher chatter_pub2 = private_nh.advertise<std_msgs::String>("chatter2", 1000);
  // CRASH: terminate called after throwing an instance of 'std::bad_alloc'

I have been debugging the error for a few days now and I can't figure out the cause. Do you have any idea on why it throws a bad_alloc error?

edit retag flag offensive close merge delete