Question

I've narrowed this down as far as I can, it seems like a bug...

#include <algorithm>
#include <vector>

int main(int argc, char *argv[])
{
  // Crashes
  std::vector<uint8_t> bs{1, 0, 0};
  std::search_n(bs.begin(), bs.end(), 3, 1);

  // Does not crash
  std::vector<uint8_t> bs{1, 0};
  std::search_n(bs.begin(), bs.end(), 2, 1);

  return 0;
}

I get

Segmentation fault: 11

I hope I'm not using std::search_n incorrectly :)

Stepping through the STL implementation doesn't seem possible at present, using LLDB.

version info:

$clang --version
Apple LLVM version 4.2 (clang-425.0.24) (based on LLVM 3.2svn)
Target: x86_64-apple-darwin12.3.0
Thread model: posix

Evidence ;)

13:06:47 ~/bug$ cat bug.cc
#include <algorithm>
#include <vector>

int main(int argc, char *argv[])
{
  std::vector<uint8_t> bs{1, 0, 0};
  std::search_n(bs.begin(), bs.end(), 3, 1);

  // std::vector<uint8_t> bs{1, 0};
  // std::search_n(bs.begin(), bs.end(), 2, 1);

  return 0;
}
13:06:52 ~/bug$ clang++ -std=c++11 -stdlib=libc++ bug.cc -o bug
13:07:36 ~/bug$ ./bug
Segmentation fault: 11
13:07:42 ~/bug$
Was it helpful?

Solution

It seems to be a bug in search_n, it crashes for me too (Xcode 4.6.1). I think in __search_n the test

if (__first == __s)  // return __last if no element matches __value_

needs to be

if (__first >= __s)  // return __last if no element matches __value_

What happens is that the algorithm starts matching, then mismatches and starts over; this new startpoint is beyond __s which is the logical last possible starting point for the length of the pattern. The old test only tested for equality, not "beyondness". With the fix it doesn't crash for me any more.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top