From b10cdd72159c4fbed1c41b7f7d0ffac5eb6c17d6 Mon Sep 17 00:00:00 2001 From: Intel A80486DX2-66 Date: Sun, 28 Jan 2024 13:49:18 +0300 Subject: [PATCH] asprintf.c: fix use of `malloc` 1. Pass `size_t` variable to `malloc` 2. Multiply the count of bytes to allocate by `sizeof(char)` --- c-programming/asprintf.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/c-programming/asprintf.c b/c-programming/asprintf.c index 4dbdda5..cdb6363 100644 --- a/c-programming/asprintf.c +++ b/c-programming/asprintf.c @@ -11,19 +11,20 @@ ssize_t asprintf(char** strp, char* format, ...) { va_list args; va_start(args, format); - ssize_t size = (ssize_t) vsnprintf(NULL, 0, format, args); - if (size < 0) { + ssize_t result = (ssize_t) vsnprintf(NULL, 0, format, args); + if (result < 0) { va_end(args); return -1; } - *strp = malloc(++size); + size_t size = (size_t) result + 1; + *strp = malloc(size * sizeof(char)); if (*strp == NULL) { va_end(args); return -1; } - ssize_t result = (ssize_t) vsnprintf(*strp, size, format, args); + result = (ssize_t) vsnprintf(*strp, size, format, args); va_end(args); if (result < 0) {