From 07b78c993c1b5a8b360ce6db11f6f79a048e8a9a Mon Sep 17 00:00:00 2001
From: Niels Lohmann <mail@nlohmann.me>
Date: Fri, 7 Jul 2017 23:37:16 +0200
Subject: [PATCH] :bug: fixed undefined behavior bug

When an empty vector was passed to the parse function, an empty iterator range was used to construct an input iterator. Unfortunately, we then cannot use the start iterator to derive a pointer from.

Found with Xcode's undefined behavior sanitizer.
---
 src/json.hpp | 13 +++++++++++--
 1 file changed, 11 insertions(+), 2 deletions(-)

diff --git a/src/json.hpp b/src/json.hpp
index 918a646b..0a588631 100644
--- a/src/json.hpp
+++ b/src/json.hpp
@@ -8886,8 +8886,17 @@ class basic_json
             static_assert(sizeof(typename std::iterator_traits<IteratorType>::value_type) == 1,
                           "each element in the iterator range must have the size of 1 byte");
 
-            return create(reinterpret_cast<const char*>(&(*first)),
-                          static_cast<size_t>(std::distance(first, last)));
+            const auto len = static_cast<size_t>(std::distance(first, last));
+            if (JSON_LIKELY(len > 0))
+            {
+                // there is at least one element: use the address of first
+                return create(reinterpret_cast<const char*>(&(*first)), len);
+            }
+            else
+            {
+                // the address of first cannot be used - use nullptr
+                return create(nullptr, len);
+            }
         }
 
         /// input adapter for array