Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this crash in libc++ std::search_n a bug?

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$
like image 572
dpj Avatar asked Apr 04 '13 11:04

dpj


1 Answers

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.

like image 193
Dix Avatar answered Dec 23 '22 01:12

Dix