PR #21321 talked about implementation-defined behavior of realloc. I poo-poohed it, and was wrong. Fix the call in <locale>. Review the others, refactored some duplicated code, and found overflow bugs (and __event_cap_ was never getting updated, either).

git-svn-id: https://llvm.org/svn/llvm-project/libcxx/trunk@220702 91177308-0d34-0410-b5e6-96231b3b80d8
diff --git a/include/locale b/include/locale
index 78f85d8..7920f5e 100644
--- a/include/locale
+++ b/include/locale
@@ -2970,6 +2970,8 @@
     size_t __cur_cap = static_cast<size_t>(__e-__b.get()) * sizeof(_Tp);
     size_t __new_cap = __cur_cap < numeric_limits<size_t>::max() / 2 ?
                        2 * __cur_cap : numeric_limits<size_t>::max();
+    if (__new_cap == 0)
+        __new_cap = sizeof(_Tp);
     size_t __n_off = static_cast<size_t>(__n - __b.get());
     _Tp* __t = (_Tp*)realloc(__owns ? __b.get() : 0, __new_cap);
     if (__t == 0)