单个实例有效,但数组显示内存损坏

时间:2018-05-18 11:40:57

标签: c++ arrays ubuntu boost shared-ptr

我面临一个奇怪的问题,它与C ++中的数组有关。基本上,我创建了一个类的两个实例,后来我使用了这些实例,这导致了内存损坏错误。如果我在不使用数组的情况下单独创建此类的两个实例,则代码可以正常工作。

请参阅下面的代码段 -

int main(int argc, char** argv)
{
    ros::init(argc, argv, "my_node");
    ros::NodeHandle nh("~");

    // this doesn't work
    PointCloudSubscriber pcs[2];
    pcs[0] = PointCloudSubscriber(nh, "/kinect1/sd/points", 1);
    pcs[1] = PointCloudSubscriber(nh, "/kinect2/sd/points", 1);

    // this works
    //PointCloudSubscriber pc1(nh, "/kinect1/sd/points", 1);
    //PointCloudSubscriber pc2(nh, "/kinect2/sd/points", 1);

    ros::Rate loop_rate(10);
    while (ros::ok())
    {
        // this doesn't work
        for (size_t i = 0; i < 2; i++)
          ROS_INFO_STREAM("Cloud topic=" << pcs[i].topic << 
                          ", size=" << pcs[i].point_cloud.data.size());

        // this works
        //ROS_INFO_STREAM("Cloud topic=" << pc1.topic << 
        //                ", size=" << pc1.point_cloud.data.size());
        //ROS_INFO_STREAM("Cloud topic=" << pc2.topic << 
        //                ", size=" << pc2.point_cloud.data.size());

        ros::spinOnce();
        loop_rate.sleep();
    }

    return 0;
}

class PointCloudSubscriber
{
private:
    ros::Subscriber subscriber;
    void callback(
        const sensor_msgs::PointCloud2ConstPtr& msg);

public:
    std::string topic;
    sensor_msgs::PointCloud2 point_cloud;
    PointCloudSubscriber(){};
    PointCloudSubscriber(
        ros::NodeHandle& node_handle,
        std::string topic_name,
        int queue_size);
};

void PointCloudSubscriber::callback(
    const sensor_msgs::PointCloud2ConstPtr& msg)
{
    point_cloud = *msg;
}

PointCloudSubscriber::PointCloudSubscriber(
    ros::NodeHandle& node_handle,
    std::string topic_name,
    int queue_size)
{
    topic = topic_name;
    subscriber = node_handle.subscribe<sensor_msgs::PointCloud2>(
        topic_name, queue_size, &PointCloudSubscriber::callback, this);
}

以下是报告的输出 -

[ INFO] [1526440334.856181149]: Cloud topic=/kinect1/sd/points, size=0
[ INFO] [1526440334.856210465]: Cloud topic=/kinect2/sd/points, size=0
*** Error in `/home/ravi/ros_ws/devel/lib/my_pcl_tutorial/check': double free or corruption (!prev): 0x000000000128f220 ***
Aborted (core dumped)

这里要注意的有趣的事情是,数组的每个元素都能够获得正确的topic,但不知何故无法获得从point_cloud分配的boost::shared_ptr属性。 / p>

为什么这么奇怪的行为?访问boost::shared_ptr是非法使用案例吗?有什么建议吗?

PS:我在Ubuntu 14.04 LTS 64位PC上使用ROS Indigo。

1 个答案:

答案 0 :(得分:3)

PointCloudSubscriber可能已被打破 1 。而不是创建PointCloudSubscriber的两个默认实例(1) 2 ,然后为它们分配“真实”值(2) 2 ,执行:

PointCloudSubscriber pcs[2] = {
    PointCloudSubscriber(nh, "/kinect1/sd/points", 1),
    PointCloudSubscriber(nh, "/kinect2/sd/points", 1)
};

1)看起来它处理资源,但只定义用户提供的构造函数。你应该注意the rule of 0/3/5

2) FYI,(1)和(2):

PointCloudSubscriber pcs[2]; // (1)
pcs[0] = PointCloudSubscriber(nh, "/kinect1/sd/points", 1); // (2)
pcs[1] = PointCloudSubscriber(nh, "/kinect2/sd/points", 1); // (2)