1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-05-31 13:28:11 +00:00

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.
This commit is contained in:
Stanisław Wiśniewski 2023-04-15 08:09:22 +02:00 committed by Andreas Kling
parent cfac3be0b3
commit 1649138a29

View file

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