[英]What is causing the segmentation fault in this code?
我的代碼中出現了分段錯誤,但是我無法跟蹤問題。 這是代碼中出現分段錯誤的部分:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.