2

I want to access listener::flow_message (a public variable) which I defined in the subscriber class, in the main() function of my code. in the below code I just did a simple printing of the flow_message parameter to show the problem.

I changed the access modifiers of the flow_message to private and protected but it gets the compilation error and I found that the only way to access this variable in the main function, is to define it as public. I can get some properties like the size of the flow_message vector, in the main using the below command:

list.flow_message.size();

but for example, when I want to access the first member of the flow_message vector, using the below command I get the segmentation fault error.

list.flow_message[0];



// this is my code for subscribing the optical flow data
// using a class for subscriber callback function:

#include<ros/ros.h>
#include<opencv_apps/FlowArrayStamped.h>
#include<opencv_apps/FlowArray.h>
#include<opencv_apps/Flow.h>
#include<opencv_apps/Point2D.h>
#include<vector>
#include<numeric>

using namespace std;

class listener
  {
     public:
     vector<opencv_apps::Flow> flow_message;
     void callback(const opencv_apps::FlowArrayStamped::ConstPtr& msg);

   };

void listener::callback(const opencv_apps::FlowArrayStamped::ConstPtr& msg)
  {
    listener::flow_message = msg->flow;
    ROS_INFO("i got it");
   }

int main(int argc, char **argv)
  {
     ros::init(argc, argv, "dataman");
     ros::NodeHandle n;
     listener list;
     ros::Subscriber sub = n.subscribe("/lk_flow/flows", 1, &listener::callback, &list);
     while(ros::ok())
       {
          cout << "this is it: " << list.flow_message[0] << endl;
          ros::spinOnce();
       }
     return 0;
  }

as I mentioned before my error is in run time:

 Segmentation fault (core dumped)

thanks for any help or comment...

Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
AMIR REZA SADEQI
  • 409
  • 2
  • 5
  • 13

1 Answers1

1

You go fetch flow_message[0] but you never add elements into the vector. If the vector is empty, then flow_message[0] don't exist.

Too add elements in the vector, you should publish a message.

But you also should check for elements in the vector:

while(ros::ok()) {
    if (list.flow_message.empty()) {
        std::cout << "no messages" << std::endl;
    } else {
        std::cout << "this is it: " << list.flow_message[0] << std::endl;
    }

    ros::spinOnce();
}
Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
  • Hi Guillaume. you are right and adding if-else part solved the problem. I checked it using the empty() function. I found that when I run the node, first it outputs 1, and after a while, it outputs 0. so at start of running the node the variable is empty and that causes the error. so thanks a lot for your fast answer!!!!!!!!! and sorry for not upvoting, because I have less than 15 reputations it does not allow me to vote. good luck! – AMIR REZA SADEQI Aug 29 '19 at 16:06