Segmentation fault (core dumped) in RosbotClass::get_laser()

In the C++ for Robotics lesson, when calling the method RosbotClass::get_laser(), I get this error: Segmentation fault (core dumped).


This is all my code:

#include “rosbot_control/rosbot_class.h”
#include <ros/ros.h>

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

RosbotClass rosbot;
float b = rosbot.get_laser(10);

What is the reason for this?

Moreover, if I add any other method of this class, the code works.
For example:

RosbotClass rosbot;
float b = rosbot.get_laser(10);
cout << b << endl;


1 Like

Hi @alexeyfenev,

Segmentation Fault happens when you try to access a variable that is still empty.

Indeed, when checking the code on ~/catkin_ws/src/cpp_course_repo/rosbot_control/src/rosbot_class.cpp, I see the code:

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

As we can see, we are just returning a value of the laser_range without checking if laser_range was already set. This is actually an error on our side.

The reason why it works after calling move() is because this move() method takes some seconds to finish, and while it is called, the laser_range receives a value through the laser_callback.

Thanks for letting us know about this error. We indeed have to fix this from our side.

1 Like

Thank you for the detailed explanation!

1 Like