Ask Your Question

How to access a public variable of subscriber class in the main function?

asked 2019-08-29 09:41:47 -0600

Amir Reza Sadeghi gravatar image

updated 2019-10-24 15:23:11 -0600

jayess gravatar image

Hi there. I want to access "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. the compilation has no error but when I run the subscriber node I get this error:

Segmentation fault (core dumped)

and this is the code:


using namespace std;

class listener
    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);
    cout << "this is it: " << list.flow_message[0] << endl;
   return 0;

maybe my question would be so simple, but I searched and worker too much on it but I could not solve it. so thanks for any help...

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2019-08-29 10:29:32 -0600

mjcarroll gravatar image

It's likely that you are trying to print the contents of the list.flow_message[0] before any data has been inserted into the vector. You should verify that the list.flow_message has contents before attempting to print.

You could use std::vector::empty or std::vector::size

edit flag offensive delete link more


Hi Carroll. you are right. 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. so the problem solved by adding and if-else part to check if the data is empty print some messages:

  cout << "the message is empty" << endl;
      cout << " the message is : " << list.flow_messge[0] << endl;

so thanks a lot for your fast answer!!!!!!!!!!!

Amir Reza Sadeghi gravatar image Amir Reza Sadeghi  ( 2019-08-29 10:47:08 -0600 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2019-08-29 09:41:47 -0600

Seen: 76 times

Last updated: Oct 24 '19