From b9463f442bb3e1a3957654acc8bcccc9b326736b Mon Sep 17 00:00:00 2001 From: obarthel Date: Fri, 8 Sep 2023 16:04:53 +0200 Subject: [PATCH] Added notes on calloc() being safe to use under certain circumstances if the number of elements or the element size happens to be 0. In effect, malloc() will decide what is going to happen. --- library/stdlib_calloc.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/library/stdlib_calloc.c b/library/stdlib_calloc.c index af90d24..366f60c 100644 --- a/library/stdlib_calloc.c +++ b/library/stdlib_calloc.c @@ -67,6 +67,9 @@ __calloc(size_t num_elements, size_t element_size, const char * file, int line) goto out; } + /* Note: malloc(0) may allocate memory and will also + * initialize its contents to zero. + */ result = __malloc(total_size, file, line); if (result == NULL) { @@ -74,7 +77,8 @@ __calloc(size_t num_elements, size_t element_size, const char * file, int line) goto out; } - memset(result, 0, total_size); + if (total_size > 0) + memset(result, 0, total_size); out: @@ -90,5 +94,5 @@ calloc(size_t num_elements, size_t element_size) result = __calloc(num_elements, element_size, NULL, 0); - return(result); + return result; }