是什么导致了这段代码中的分段错误? [英] What is causing the segmentation fault in this code?

查看:39
本文介绍了是什么导致了这段代码中的分段错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码出现分段错误,但我无法追踪问题.这是发生分段错误的代码部分:

I am getting a segmentation fault in my code, but I'm having trouble tracking down the problem. This is the section of the code where the segmentation fault seems to take place:

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

运行时只打印以下两行

Test 1
Test 2

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

Based off the print lines it seems like the code only loops once and then a segmentation fault occurs.

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

What could be causing this?

推荐答案

您正在保存一个局部变量的地址,该地址已在您的列表中销毁.

You are saving an address of local variable which is destroyed in your list.

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

所以很可能你稍后会访问被删除的内存

So it's likely that you are accessing the deleted memory later

使用std::vector>:

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

这篇关于是什么导致了这段代码中的分段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆