令人困惑的SegFault涉及STL排序算法

时间:2010-03-14 03:04:55

标签: c++ algorithm stl vector segmentation-fault

我正在尝试使用STL重新创建编程珍珠的第15列中的程序。我正在尝试使用字符串和索引向量创建后缀数组。我记录了我在一个名为input的字符串中读取的单词列表,该字符串充当由我在程序开头从stdin读取的''分隔的单词列表。一切都按预期工作,直到我到达代码的排序部分。我想使用STL的排序算法,但我对我似乎正在创建的seg错误感到非常困惑。

我有:

vector<unsigned int> words;

和全局变量

string input;

我定义了自定义比较功能:

bool wordncompare(unsigned int f, unsigned int s) {
  int n = 2;

  while (((f < input.size()) && (s < input.size()))
         && (input[f] == input[s])) {
    if ((input[f] == ' ') && (--n == 0)) {
      return false;
    }

    f++;
    s++;
  }

  return true;
}

当我运行代码时:

sort(words.begin(), words.end());

该计划顺利退出。

但是,当我运行代码时:

sort(words.begin(), words.end(), wordncompare);

我在STL内部生成了一个SegFault。

GDB反向跟踪代码如下所示:

#0  0x00007ffff7b79893 in std::string::size() const () from /usr/lib/gcc/x86_64-pc-linux-gnu/4.3.4/libstdc++.so.6
#1  0x0000000000400f3f in wordncompare (f=90, s=0) at text_gen2.cpp:40
#2  0x000000000040188d in     std::__unguarded_linear_insert<__gnu_cxx::__normal_iterator<unsigned int*, std::vector<unsigned int, std::allocator<unsigned int> > >, unsigned int, bool (*)(unsigned int, unsigned int)> (__last=..., __val=90, __comp=0x400edc <wordncompare(unsigned int, unsigned int)>)
at /usr/lib/gcc/x86_64-pc-linux-gnu/4.3.4/include/g++-v4/bits/stl_algo.h:1735
#3  0x00000000004018df in std::__unguarded_insertion_sort<__gnu_cxx::__normal_iterator<unsigned int*, std::vector<unsigned int, std::allocator<unsigned int> > >, bool (*)(unsigned int, unsigned int)> (__first=..., __last=..., __comp=0x400edc <wordncompare(unsigned int, unsigned int)>)
at /usr/lib/gcc/x86_64-pc-linux-gnu/4.3.4/include/g++-v4/bits/stl_algo.h:1812  
#4  0x0000000000402562 in std::__final_insertion_sort<__gnu_cxx::__normal_iterator<unsigned int*, std::vector<unsigned int, std::allocator<unsigned int> > >, bool (*)(unsigned int, unsigned int)> (__first=..., __last=..., __comp=0x400edc <wordncompare(unsigned int, unsigned int)>)
at /usr/lib/gcc/x86_64-pc-linux-gnu/4.3.4/include/g++-v4/bits/stl_algo.h:1845
#5  0x0000000000402c20 in std::sort<__gnu_cxx::__normal_iterator<unsigned int*, std::vector<unsigned int, std::allocator<unsigned int> > >, bool (*)(unsigned int, unsigned int)> (__first=..., __last=..., __comp=0x400edc <wordncompare(unsigned int, unsigned int)>)
at /usr/lib/gcc/x86_64-pc-linux-gnu/4.3.4/include/g++-v4/bits/stl_algo.h:4822
#6  0x00000000004012d2 in main (argc=1, args=0x7fffffffe0b8) at text_gen2.cpp:70

我在另一个程序中有类似的代码,但在该程序中我使用向量而不是向量。对于我的生活,我无法弄清楚我做错了什么。谢谢!

1 个答案:

答案 0 :(得分:10)

很可能你的比较器不满足严格的弱排序;例如,它违反了传递性,因为存在一些值的环,使得A <1。 B,B&lt; C和C&lt; A.这是requirements。我没有看到它在我的头顶,但我会继续盯着它看几分钟。