Bewildering SegFault Using STL Sort Algorithm

I am trying to recreate a program in a column of 15 programming gems using STL. I am trying to create a suffix array using a string and an index vector. I write a list of words that I read in a line called input, which acts like a list of words separated by a character '', which I read from stdin at the beginning of the program. Everything works as expected until I get to the sorting part of the code. I would like to use the STL sorting algorithm, but I'm completely puzzled by the seg error that I seem to be creating.

I have:

vector<unsigned int> words;

and global variable

string input;

I define my custom compare function:

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;
}

When I run the code:

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

The program comes out smoothly.

However, when I run the code:

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

I create SegFault deep inside the STL.

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

, . , . !

+5
1

, ; , , , , A < B, B < C C < A. . , .

+10

All Articles