[libvirt PATCH 08/11] tests: Prevent malloc with size 0

Tim Wiederhake posted 11 patches 5 years ago
There is a newer version of this series
[libvirt PATCH 08/11] tests: Prevent malloc with size 0
Posted by Tim Wiederhake 5 years ago
Found by clang-tidy's "clang-analyzer-optin.portability.UnixAPI" check.

Signed-off-by: Tim Wiederhake <twiederh@redhat.com>
---
 tests/commandhelper.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/tests/commandhelper.c b/tests/commandhelper.c
index ba5681b715..9394a42726 100644
--- a/tests/commandhelper.c
+++ b/tests/commandhelper.c
@@ -99,7 +99,7 @@ int main(int argc, char **argv) {
         origenv++;
     }
 
-    if (!(newenv = malloc(sizeof(*newenv) * n)))
+    if ((n == 0) || !(newenv = malloc(sizeof(*newenv) * n)))
         abort();
 
     origenv = environ;
-- 
2.26.2

Re: [libvirt PATCH 08/11] tests: Prevent malloc with size 0
Posted by Peter Krempa 5 years ago
On Thu, Jan 28, 2021 at 11:24:38 +0100, Tim Wiederhake wrote:
> Found by clang-tidy's "clang-analyzer-optin.portability.UnixAPI" check.
> 
> Signed-off-by: Tim Wiederhake <twiederh@redhat.com>
> ---
>  tests/commandhelper.c | 2 +-
>  1 file changed, 1 insertion(+), 1 deletion(-)
> 
> diff --git a/tests/commandhelper.c b/tests/commandhelper.c
> index ba5681b715..9394a42726 100644
> --- a/tests/commandhelper.c
> +++ b/tests/commandhelper.c
> @@ -99,7 +99,7 @@ int main(int argc, char **argv) {
>          origenv++;
>      }
>  
> -    if (!(newenv = malloc(sizeof(*newenv) * n)))
> +    if ((n == 0) || !(newenv = malloc(sizeof(*newenv) * n)))
>          abort();

This doesn't seem to be an abort-worthy case. It's unlikely but the
environment can contain no variables. Also it makes stuff hard to debug.
If n==0 is indeed a problem an error should be reported.

>  
>      origenv = environ;
> -- 
> 2.26.2
>