Unexplainable Segfault (double free) in templated Subscriber (polling)
Hey ROS-Community,
I have a very weird error in the attached templated subscriber class, that happens very(!) seldom but is quite frustrating.
Class:
/*
* GenericSubscriber.hpp
*
* Created on: Feb 29, 2012
* Author: mriedel
*/
#ifndef GENERICSUBSCRIBER_HPP_
#define GENERICSUBSCRIBER_HPP_
#include <telekyb_defines/telekyb_defines.hpp>
#include <boost/thread/mutex.hpp>
#include <ros/node_handle.h>
namespace TELEKYB_NAMESPACE
{
template <class T_>
class GenericSubscriber {
protected:
T_ lastMsg;
boost::mutex lastMsgLock;
// Subscriber
ros::Subscriber sub;
void msgCallback(boost::shared_ptr<T_ const> msg) {
boost::mutex::scoped_lock(lastMsgLock);
lastMsg = *msg; // copy
}
public:
GenericSubscriber(ros::NodeHandle handle, const std::string& topicName, int queue_size) {
sub = handle.subscribe(topicName, queue_size, &GenericSubscriber<T_>::msgCallback, this);
}
virtual ~GenericSubscriber() {};
T_ getLastMsg() const {
boost::mutex::scoped_lock(lastMsgLock);
return lastMsg; // implicit copy. Maybe we can do this more efficient?
}
};
}
#endif /* GENERICSUBSCRIBER_HPP_ */
This class enables me to receive generic messages and save the last message in a variable and collect the message with getLastMsg() when needed. Very simple.
Of course it's not the most efficient way to do this (copying the message twice), but it's working for our application. However, every once in a while (seldom) my program crashes when calling getLastMsg() (double free). I don't see where the problem could be located (if in my code or the C++ copy constructor of ROS msgs). Any tips and comments are greatly appreciated.
Thanks! Martin