【问题标题】:Segmentation fault when using a vector in c++在 C++ 中使用向量时出现分段错误
【发布时间】:2014-04-11 21:40:54
【问题描述】:

使用向量时出现分段错误似乎是一个常见问题,但我似乎仍然无法解决我的问题。我不清楚为什么 getArmPose 函数代码段中的向量会导致分段错误。

class CytonServer
{
public:
    CytonServer();
private:
    std::vector <double> arm_pos_;
....


    void CytonServer::publish_Callback()
    { 
     ROS_INFO("PUBLISH");
      boost::mutex::scoped_lock lock(publish_mutex_);
      if (teleop_vehicle_==false)
      {
         ROS_INFO("Publishing ");
         end_effector_type = "point_end_effector"; 

         //Here is the culprip see function below
         arm_pos_ = cytonCommands.getArmPose();
         .....
       }
    }

//In a different file is the following method that is called and is causing the segmentation fault


std::vector <double> EcCytonCommands::getArmPose()
{

  double x,y,z;
  std::vector<double> arm_pos_;
    EcManipulatorEndEffectorPlacement actualEEPlacement;
    EcCoordinateSystemTransformation actualCoord;

    getActualPlacement(actualEEPlacement);
    actualCoord=actualEEPlacement.offsetTransformations()[0].coordSysXForm();

    arm_pos_.push_back(actualCoord.translation().x());
    arm_pos_.push_back(actualCoord.translation().y());

    arm_pos_.push_back(actualCoord.translation().z());

    return arm_pos_;
}

对于如何解决此问题的任何帮助将不胜感激。

【问题讨论】:

  • 看起来该向量不会导致此示例中的任何问题。尝试替换 getArmPose() 中的内容以不进行任何查询,而只需 push_back() 一些测试值。看看它是否仍然在该函数中出现段错误。
  • 您能否更具体地说明段错误发生的位置?使用像 valgrind 这样的工具,它是检测内存泄漏、段错误、未初始化值等的好工具。
  • 向量段错误几乎总是来自读取不存在的索引。
  • 不要使用std::vector&lt;&gt; 运送 3 双份。由于数字在编译时是已知的(并且对象是微不足道的),最好使用std::array
  • translation()和x()的函数签名是什么?

标签: c++ vector segmentation-fault


【解决方案1】:

感谢您的快速反馈。我们发现问题不在于向量,而是我调用的第 3 方应用程序不是线程安全的。添加互斥锁已解决该问题。

std::vector <double> EcCytonCommands::getArmPose()
{
  boost::mutex::scoped_lock lock(publish_mutex_);
  std::vector<double> arm_pos_;

    EcManipulatorEndEffectorPlacement actualEEPlacement;
    EcCoordinateSystemTransformation actualCoord;

    getActualPlacement(actualEEPlacement);
    actualCoord=actualEEPlacement.offsetTransformations()[0].coordSysXForm();

    arm_pos_.push_back(actualCoord.translation().x());
    arm_pos_.push_back(actualCoord.translation().y());

    arm_pos_.push_back(actualCoord.translation().z());

    std::cout << "size, x, y, z: " <<arm_pos_.size()<< " "<<arm_pos_[0] <<", "<<arm_pos_[1]<<", "<<arm_pos_[2] <<std::endl;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    • 1970-01-01
    相关资源
    最近更新 更多