Jigglypuff
Jigglypuff

Reputation: 1463

What is causing the segmentation fault in this code?

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");
}

When run this prints only the following two lines

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?

Upvotes: 0

Views: 767

Answers (1)

Andrew
Andrew

Reputation: 24846

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

Use std::vector<std::shared_ptr<Robot>>:

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

Upvotes: 2

Related Questions