From: Haocheng Zhang Date: Wed, 15 Jun 2016 03:25:09 +0000 (-0700) Subject: fix bug for nullptr in qfind X-Git-Tag: 2016.07.26~140 X-Git-Url: http://plrg.eecs.uci.edu/git/?a=commitdiff_plain;h=1de25658576a9d1fb131722f67925039a14c5390;p=folly.git fix bug for nullptr in qfind Summary: Fix bug for passing null pointer to memchr function, which requires the first argument to never be null. Reviewed By: luciang Differential Revision: D3432130 fbshipit-source-id: 419924dd214d9f641d3d46335dae6abbe44ca751 --- diff --git a/folly/Range.h b/folly/Range.h index 4a064916..e4be2b06 100644 --- a/folly/Range.h +++ b/folly/Range.h @@ -1085,6 +1085,10 @@ size_t rfind(const Range& haystack, // specialization for StringPiece template <> inline size_t qfind(const Range& haystack, const char& needle) { + // memchr expects a not-null pointer, early return if the range is empty. + if (haystack.empty()) { + return std::string::npos; + } auto pos = static_cast( ::memchr(haystack.data(), needle, haystack.size())); return pos == nullptr ? std::string::npos : pos - haystack.data(); @@ -1092,6 +1096,10 @@ inline size_t qfind(const Range& haystack, const char& needle) { template <> inline size_t rfind(const Range& haystack, const char& needle) { + // memchr expects a not-null pointer, early return if the range is empty. + if (haystack.empty()) { + return std::string::npos; + } auto pos = static_cast( ::memrchr(haystack.data(), needle, haystack.size())); return pos == nullptr ? std::string::npos : pos - haystack.data(); @@ -1101,6 +1109,10 @@ inline size_t rfind(const Range& haystack, const char& needle) { template <> inline size_t qfind(const Range& haystack, const unsigned char& needle) { + // memchr expects a not-null pointer, early return if the range is empty. + if (haystack.empty()) { + return std::string::npos; + } auto pos = static_cast( ::memchr(haystack.data(), needle, haystack.size())); return pos == nullptr ? std::string::npos : pos - haystack.data(); @@ -1109,6 +1121,10 @@ inline size_t qfind(const Range& haystack, template <> inline size_t rfind(const Range& haystack, const unsigned char& needle) { + // memchr expects a not-null pointer, early return if the range is empty. + if (haystack.empty()) { + return std::string::npos; + } auto pos = static_cast( ::memrchr(haystack.data(), needle, haystack.size())); return pos == nullptr ? std::string::npos : pos - haystack.data();