From 17014bb8de951ca900cc2915b424621a935a0d10 Mon Sep 17 00:00:00 2001
From: Bananymous <oskari.alaranta@bananymous.com>
Date: Tue, 28 Jan 2025 22:40:06 +0200
Subject: [PATCH] LibC: Fix strndup

I did not null terminate short strndup copies :D
---
 userspace/libraries/LibC/string.cpp | 13 +++++++------
 1 file changed, 7 insertions(+), 6 deletions(-)

diff --git a/userspace/libraries/LibC/string.cpp b/userspace/libraries/LibC/string.cpp
index 8a7168efb..0117f3088 100644
--- a/userspace/libraries/LibC/string.cpp
+++ b/userspace/libraries/LibC/string.cpp
@@ -189,27 +189,28 @@ int strcoll(const char* s1, const char* s2)
 
 char* strdup(const char* str)
 {
-	const size_t size = strlen(str) + 1;
+	const size_t size = strlen(str);
 
-	char* new_str = (char*)malloc(size);
+	char* new_str = (char*)malloc(size + 1);
 	if (new_str == nullptr)
 		return nullptr;
 
 	memcpy(new_str, str, size);
+	new_str[size] = '\0';
 	return new_str;
 }
 
 char* strndup(const char* str, size_t size)
 {
-	if (strlen(str) < size)
-		size = strlen(str);
-	size += 1;
+	if (size_t len = strlen(str); len < size)
+		size = len;
 
-	char* new_str = (char*)malloc(size);
+	char* new_str = (char*)malloc(size + 1);
 	if (new_str == nullptr)
 		return nullptr;
 
 	memcpy(new_str, str, size);
+	new_str[size] = '\0';
 	return new_str;
 }