我一直在拔头发来找出这个段错误,并决定寻求帮助。
我有一个boost::multi_index
容器,其中包含(string, string, double)
并且在某些时候遇到了段错误。
这是我的代码的简化版本:
#include<iostream>
....
// mySet is a multi_index container which contains <(string str1), (string str2), (double val)>
typedef mySet::index<str1>::type set_by_str1;
...
for(unsigned int i=0; i < token.size(); ++i)
{
set_by_str1::iteration it = myContainer.get<str1>().find(token[i]);
while(it->str1() == token[i])
{
cout << it->str1() << ", " << it->str2() << ", " << it->val << endl;
}
*it++;
}
这段代码看起来工作得很好,但它只有在遇到某个特定的令牌时才会崩溃。(相反地,当它不符合令牌时它永远不会崩溃)。
我猜这是因为it
超出了容器本身的范围,但不明白它是如何发生的。
GDB 错误消息显示:
Program received signal SIGSEGV, Segmentation fault.
0x08052e83 in std::string::size (this=0x806e190) at /usr/include/c++/4.4/bits/basic_string.h:629
629 { return _M_rep()->_M_length; }
(gdb) bactrace full
#0 0x08052e83 in std::string::size (this=0x806e190) at /usr/include/c++/4.4/bits/basic_string.h:629
No locals.
#1 0x08050475 in std::operator<< <char, std::char_traits<char>, std::allocator<char> > (__os=..., __str=...)
at /usr/include/c++/4.4/bits/basic_string.h:2503
No locals.
#2 0x0804e4e0 in MyClass:MyFunction (this=0xbffff534) at src/MyCode.cpp:353 (This is where while condition exists)
... dump of HUGE trace for multi_index ...
当我调用 while 条件时,它显然会崩溃it->str1()
,而不是因为令牌向量。我怎样才能防止这种情况?我试图在if(it == myContainer.get<str1>().end()) break;
下面添加*it++
,但没有帮助。
有人能给我一些线索吗?
谢谢!