Segmentation fault (core dumped) - C++ for Robotics

Have reported this through the workspace, but was asked to post it here.

In “C++ for Robotics - section 4: Arrays” a Segmentation fault was occurring. No other error messages given. It was found that rosbot.move() had to be called before rosbot.get_laser(int idx) and therefore has to be a bug in the underlying source code somewhere i.e. something wasn’t initialized.

Possible solution:
Under the script rosbot_class.cpp in each of the move commands the publishing rate has been set, whereas within the get_laser method it is not set.
Found that calling ros::spinOnce() solved the segmentation fault, needs to be added to get_laser()

Move:

void RosbotClass::move() {
  // Rate of publishing
  ros::Rate rate(10);

  ros::Time start_time = ros::Time::now();
  ros::Duration timeout(2.0); // Timeout of 2 seconds
  while (ros::Time::now() - start_time < timeout) {
    ros::spinOnce();
    vel_msg.linear.x = +0.5;
    vel_msg.angular.z = 0.0;
    vel_pub.publish(vel_msg);
    rate.sleep();
  }
  vel_msg.linear.x = 0.0;
  vel_msg.angular.z = 0.0;
  vel_pub.publish(vel_msg);
}

Laser:

float RosbotClass::get_laser(int index) { return laser_range[index]; }

float *RosbotClass::get_laser_full() {
  float *laser_range_pointer = laser_range.data();
  return laser_range_pointer;
}

This error happened again in the next section: Classes.
Even though I was calling move() beforehand I was still getting this error at the end of my program, whereas it previously it just wouldn’t run at all.

Here is my solution that created the fault:

Edit: below had a circular call for the move() method.

#include "rosbot_control/rosbot_class.h"
#include <ros/ros.h>

#include <string>

using namespace std;

class RosBotWithNav : private RosbotClass {
public:
  void turn_left_90_deg() { this->turn("counterclockwise", 3); }

  void turn_right_90_deg() { this->turn("clockwise", 3); }

  void move_up_to_next() {
    this->move_forward(1);
    while (this->get_laser(0) > 2) {
      this->move_forward(1);
    }
  }

  void move_along_obstacle() {
    this->move_forward(1);
    while (this->get_laser(180) < 5) {
      this->move_forward(1);
    }
  }

  void move() { this->move(); } // <-- circular error
};

int main(int argc, char **argv) {
  ros::init(argc, argv, "Rosbot_move_node");

  RosBotWithNav rosbot;
  rosbot.move_up_to_next();
  rosbot.turn_left_90_deg();
  rosbot.move_along_obstacle();
  rosbot.turn_right_90_deg();
  rosbot.move();
}
2 Likes

Hello @josiahbrough ,

Many thanks for the feedback. I’ve been doing some tests to confirm this behavior. I’ve created an issue and we will fix it as soon as possible.