Bewildering SegFault involving STL sort algorithm.

Posted by just_wes on Stack Overflow See other posts from Stack Overflow or by just_wes
Published on 2010-03-14T03:04:54Z Indexed on 2010/03/14 3:15 UTC
Read the original article Hit count: 340

Filed under:
|
|
|
|

Hello everybody,

I am completely perplexed at a seg fault 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 = k;

  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 exits smoothly.

However, when I run the code:

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

I generate a SegFault deep within the STL.

The GDB back-trace code looks like this:

#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

I have similar code in another program, but in that program I am using a vector instead of vector. For the life of me I can't figure out what I'm doing wrong. Thanks!

© Stack Overflow or respective owner

Related posts about c++

Related posts about segmentation-fault