OPENSSL_strndup should not return NULL given {NULL, 0}.

The NUL-terminated representation of the empty string is a non-NULL
one-byte array, not NULL. This fills in the last of the empty string
cases in https://boringssl-review.googlesource.com/c/boringssl/+/49006/

Change-Id: I66c09dc3223f762b708612987b26c90e41e27c4a
Reviewed-on: https://boringssl-review.googlesource.com/c/boringssl/+/49009
Reviewed-by: Adam Langley <agl@google.com>
diff --git a/crypto/crypto_test.cc b/crypto/crypto_test.cc
index 03b909d..bf0bcd7 100644
--- a/crypto/crypto_test.cc
+++ b/crypto/crypto_test.cc
@@ -20,6 +20,7 @@
 #include <openssl/base.h>
 #include <openssl/crypto.h>
 #include <openssl/cipher.h>
+#include <openssl/mem.h>
 
 #include <gtest/gtest.h>
 
@@ -35,6 +36,12 @@
             std::string(OPENSSL_VERSION_TEXT).substr(0, strlen(expected)));
 }
 
+TEST(CryptoTest, Strndup) {
+  bssl::UniquePtr<char> str(OPENSSL_strndup(nullptr, 0));
+  EXPECT_TRUE(str);
+  EXPECT_STREQ("", str.get());
+}
+
 #if defined(BORINGSSL_FIPS_COUNTERS)
 TEST(CryptoTest, FIPSCountersEVP) {
   constexpr struct {
diff --git a/crypto/mem.c b/crypto/mem.c
index cc764cc..4ccc263 100644
--- a/crypto/mem.c
+++ b/crypto/mem.c
@@ -328,22 +328,15 @@
 }
 
 char *OPENSSL_strndup(const char *str, size_t size) {
-  char *ret;
-  size_t alloc_size;
-
-  if (str == NULL) {
-    return NULL;
-  }
-
   size = OPENSSL_strnlen(str, size);
 
-  alloc_size = size + 1;
+  size_t alloc_size = size + 1;
   if (alloc_size < size) {
     // overflow
     OPENSSL_PUT_ERROR(CRYPTO, ERR_R_MALLOC_FAILURE);
     return NULL;
   }
-  ret = OPENSSL_malloc(alloc_size);
+  char *ret = OPENSSL_malloc(alloc_size);
   if (ret == NULL) {
     OPENSSL_PUT_ERROR(CRYPTO, ERR_R_MALLOC_FAILURE);
     return NULL;