2017-09-18 57 views
-4

我使用C++ 11用gcc 4.8.5和在我的代碼差錯部分是這樣的:段錯誤與共享指針

vector<shared_ptr<My_Type>> items; 
for(int i = 0; i < num_dequeued; i++) { 
    auto & item = task_items[i]; 
    items.push_back(item->my_type_); //here item->my_type_ is declared as 'shared_ptr<My_Type>', and this is the error line 
} 

和gdb表示:

Program received signal SIGSEGV, Segmentation fault. 
[Switching to Thread 0x7fffc6ffd700 (LWP 9632)] 
0x000000000043254c in __shared_ptr (this=0x7fffb19ed7d0) at /usr/include/c++/4.8.2/bits/shared_ptr_base.h:779 
779  __shared_ptr(const __shared_ptr&) noexcept = default; 

我不不明白爲什麼items.push_back(item->my_type_)會導致段錯誤,所以如何解決它?只有

+0

是一個有效的指針? –

+0

它似乎很有可能'task_items [i]'是'nullptr'(或空的共享指針) –

+0

你介意嘗試'if(item){items.push_back(item)}'嗎? –

回答

1

兩種可能性:

  1. 你的指針是nullptr。 (item->my_type_
  2. num_dequed是否會通過索引? (items[i]訪問過去的元素,但並沒有崩潰,後來崩潰)

我認爲這些是唯一的可能性(在本地)看你的代碼。否則,我很確定這個問題在別的地方。

+0

我測試過了,既沒有item也沒有my_type_爲空 –

+1

我建議你展示更多的上下文。從上下文中可以看出,我找不到任何其他問題。所以這意味着問題在別的地方,除非我錯過了一些東西。 @MickeyShine –

+0

我加了'if(!item-> my_type_)..',這次gdb顯示'item-> my_type_'出現段錯誤。根據http://en.cppreference.com/w/cpp/memory/shared_ptr/operator_bool,這行只檢查存儲的指針是否爲null –