From ae71ff9c4277a625586a782f963629c1c2789982 Mon Sep 17 00:00:00 2001
From: Intel A80486DX2-66 <larry.holst@disroot.org>
Date: Mon, 30 Dec 2024 23:49:50 +0300
Subject: [PATCH] asprintf.c: fix the critical bug: copy the arguments

---
 c-programming/strings/asprintf.c | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)

diff --git a/c-programming/strings/asprintf.c b/c-programming/strings/asprintf.c
index bf1c908..ecb0f48 100644
--- a/c-programming/strings/asprintf.c
+++ b/c-programming/strings/asprintf.c
@@ -12,9 +12,13 @@ ssize_t asprintf(char** strp, char* format, ...) {
 	va_list args;
 	va_start(args, format);
 
+	va_list args_copy;
+	va_copy(args_copy, args);
+
 	ssize_t result = (ssize_t) vsnprintf(NULL, 0, format, args);
 	if (result < 0) {
 		va_end(args);
+		va_end(args_copy);
 		return -1;
 	}
 
@@ -22,11 +26,13 @@ ssize_t asprintf(char** strp, char* format, ...) {
 	*strp = malloc(size * sizeof(char));
 	if (*strp == NULL) {
 		va_end(args);
+		va_end(args_copy);
 		return -1;
 	}
 
-	result = (ssize_t) vsnprintf(*strp, size, format, args);
+	result = (ssize_t) vsnprintf(*strp, size, format, args_copy);
 	va_end(args);
+	va_end(args_copy);
 
 	if (result < 0) {
 		free(*strp);