Segmentation fault while trying to access subscribed array
Hi everyone,
I have the following callback function to subscribe to a message of type nav_msgs::Path.
void planCallback(const nav_msgs::Path::ConstPtr& msg)
{
int i=0;
std::vector<geometry_msgs::PoseStamped> data = msg->poses;
for(std::vector<geometry_msgs::PoseStamped>::const_iterator it= data.begin(); it!= data.end(); ++it)
{
//gPlan.poses.header.stamp =
gPlan.poses[i].header = it->header;
gPlan.poses[i].pose = it->pose;
i++;
}
}
In the main code, inside the while loop, I try to access the elements of the array subscribed to as follows:
for(int i=0; i<=gPlan.poses.size(); i++)
{
wp.pose.pose.position = gPlan.poses[i].pose.position;
}
wp is a variable of a type that has geometry_msgs/PoseStamped pose has one of its members.
I get a segmentation error when I try to run this. Please help!
Where is
gPlan
instantiated? Are you sure thatgPlan.poses
has the same number of entries asmsg->poses
? It should because you are using an iterator frommsg->poses
to access and fill entries in gPlan, but if you haven't allocated memory of sufficient length you'll definitely get a segfaultYou should use the std::vector::push_back() method to add elements into the array. It's initially empty so your trying to write to unallocated space.
I hate to repeat myself, but I gave you the solution to this in your last question. You can replace 6 lines with a single simpler one which will work.