在自定义类型的向量(基本上是图形节点)上调用insert函数时,我遇到了一个奇怪的错误。以下是生成seg错误的代码:
69 for (int i = 0; i < size; i++) {
70 PDTNode * node = arguments[i]->getNode();
71 //addChild(node);
72 children.insert(it, node); // children is vector <PDTNode*>
73 it++;
74 node->addParent(this);
75 }
我仔细检查所有输入,一切正常,不是NULL。下面是我为seg错误获得的gdb堆栈跟踪:
#0 0x00007ffff4793202 in ?? () from /lib/libc.so.6
#1 0x00007ffff479163a in memmove () from /lib/libc.so.6
#2 0x00000000004289f1 in std::__copy_move<false, true, std::random_access_iterator_tag>::__copy_m<PDTNode*> (__first=0x100bd60, __last=0x10053c8,
__result=0x1001840) at /usr/include/c++/4.4/bits/stl_algobase.h:378
#3 0x00000000004289ab in std::__copy_move_a<false, PDTNode**, PDTNode**> (__first=0x100bd60, __last=0x10053c8, __result=0x1001840)
at /usr/include/c++/4.4/bits/stl_algobase.h:397
#4 0x0000000000428973 in std::__copy_move_a2<false, PDTNode**, PDTNode**> (__first=0x100bd60, __last=0x10053c8, __result=0x1001840)
at /usr/include/c++/4.4/bits/stl_algobase.h:436
#5 0x000000000042891d in std::copy<PDTNode**, PDTNode**> (__first=0x100bd60, __last=0x10053c8, __result=0x1001840)
at /usr/include/c++/4.4/bits/stl_algobase.h:468
#6 0x00000000004288dc in std::__uninitialized_copy<true>::uninitialized_copy<PDTNode**, PDTNode**> (__first=0x100bd60, __last=0x10053c8, __result=0x1001840)
at /usr/include/c++/4.4/bits/stl_uninitialized.h:93
#7 0x0000000000428847 in std::uninitialized_copy<PDTNode**, PDTNode**> (__first=0x100bd60, __last=0x10053c8, __result=0x1001840)
at /usr/include/c++/4.4/bits/stl_uninitialized.h:117
#8 0x00000000004287b8 in std::__uninitialized_copy_a<PDTNode**, PDTNode**, PDTNode*> (__first=0x100bd60, __last=0x10053c8, __result=0x1001840)
at /usr/include/c++/4.4/bits/stl_uninitialized.h:257
#9 0x0000000000428684 in std::__uninitialized_move_a<PDTNode**, PDTNode**, std::allocator<PDTNode*> > (__first=0x100bd60, __last=0x10053c8,
__result=0x1001840, __alloc=...) at /usr/include/c++/4.4/bits/stl_uninitialized.h:267
#10 0x000000000042812e in std::vector<PDTNode*, std::allocator<PDTNode*> >::_M_insert_aux (this=0x1002810, __position=..., __x=@0x7fffffffd538)
at /usr/include/c++/4.4/bits/vector.tcc:338
#11 0x000000000043c46d in std::vector<PDTNode*, std::allocator<PDTNode*> >::insert (this=0x1002810, __position=..., __x=@0x7fffffffd538)
at /usr/include/c++/4.4/bits/vector.tcc:126
#12 0x00000000004d3ea9 in PDTFunctionDec::setArguments (this=0x10027e0, arguments=...) at PDTFunction.cpp:72
非常感谢任何帮助。
谢谢
答案 0 :(得分:8)
我猜它是一个迭代器,但是通过插入一个元素,你会触发容器中元素的重定位,从而使迭代器无效。这应该是您的分段错误的原因。
答案 1 :(得分:4)
插入向量可以使迭代器无效:
children.insert(it, node); // this can invalidate `it', triggering a
// segfault during the next iteration