c++ - 是什么导致此代码中的段错误?

标签 c++ pointers vector segmentation-fault

我的代码中出现段错误,但我无法找到问题所在。这是似乎发生段错误的代码部分:

for (i = 0; i < ROBOTCOUNT; i++)
{
    ROS_INFO("Test 1");
    Robot r;
    robotList.push_back(&r);
    ROS_INFO("Test 2");
}

运行时仅打印以下两行

Test 1
Test 2

根据打印行,代码似乎只循环一次,然后发生段错误。

这可能是什么原因造成的?

最佳答案

你正在保存一个在你的列表中被销毁的局部变量的地址。

for (i = 0; i < ROBOTCOUNT; i++)
{
    ROS_INFO("Test 1");
    Robot r; <== local variable
    robotList.push_back(&r); <== save address of local
    ROS_INFO("Test 2");
}  <== r is destroyed

所以很可能您稍后正在访问已删除的内存

使用 std::vector<std::shared_ptr<Robot>> :

std::vector<std::shared_ptr<Robot>> v;
std::shared_ptr<Robot> ptr( new Robot() );
v.push_back(ptr)

关于c++ - 是什么导致此代码中的段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12016215/

相关文章:

c++ - boost::detail::atomic_count 线程安全吗?

c++ - 恒定的正确性

c++ - 更新 vector 内同一基类的不同派生类的数据成员

c - 指针解除引用、坏指针

python - Numpy 矩阵乘法返回 nan

c++ - 找不到-lX11

c++ - 将 MPI 与线程一起使用的正确方法是什么

c++ - 当我输入 3 个偶数时,它显示我输入 4

c++ - 分配 'this' 指针的内存

php - 在函数上使用 php 指针?