From 1de25658576a9d1fb131722f67925039a14c5390 Mon Sep 17 00:00:00 2001 From: Haocheng Zhang Date: Tue, 14 Jun 2016 20:25:09 -0700 Subject: [PATCH] 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 --- folly/Range.h | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) 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(); -- 2.34.1