Bläddra i källkod

LibC: Return nullptr if allocation fails in strdup() and strndup()

If allocation would fail, we would continue to UB at memcpy
and nullptr dereference before returning.
Stanisław Wiśniewski 2 år sedan
förälder
incheckning
1649138a29
1 ändrade filer med 4 tillägg och 0 borttagningar
  1. 4 0
      Userland/Libraries/LibC/string.cpp

+ 4 - 0
Userland/Libraries/LibC/string.cpp

@@ -72,6 +72,8 @@ char* strdup(char const* str)
 {
     size_t len = strlen(str);
     char* new_str = (char*)malloc(len + 1);
+    if (!new_str)
+        return nullptr;
     memcpy(new_str, str, len);
     new_str[len] = '\0';
     return new_str;
@@ -82,6 +84,8 @@ char* strndup(char const* str, size_t maxlen)
 {
     size_t len = strnlen(str, maxlen);
     char* new_str = (char*)malloc(len + 1);
+    if (!new_str)
+        return nullptr;
     memcpy(new_str, str, len);
     new_str[len] = 0;
     return new_str;