From 9958d446a63fbad0eb8828740782e472486b16f7 Mon Sep 17 00:00:00 2001 From: Paul Cercueil Date: Fri, 10 Jun 2022 14:26:46 +0100 Subject: [PATCH] context: Don't create channels mask when IIO device has 0 channels When a IIO device has 0 channels, there's no point in creating a channels mask. This fixes an undefined behaviour, as the call to iio_create_channels_mask() could result in calling malloc(0). To prevent this from happening again, iio_create_channels_mask() will now check the validity of its parameter. Signed-off-by: Paul Cercueil --- context.c | 8 +++++--- mask.c | 3 +++ 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/context.c b/context.c index 617ff11dc..afb3be6b2 100644 --- a/context.c +++ b/context.c @@ -365,9 +365,11 @@ int iio_context_init(struct iio_context *ctx) int ret; for (i = 0; i < ctx->nb_devices; i++) { - ret = iio_device_alloc_mask(ctx->devices[i]); - if (ret) - return ret; + if (ctx->devices[i]->nb_channels) { + ret = iio_device_alloc_mask(ctx->devices[i]); + if (ret) + return ret; + } } for (i = 0; i < ctx->nb_devices; i++) diff --git a/mask.c b/mask.c index 4a0bf009b..39f9c96c6 100644 --- a/mask.c +++ b/mask.c @@ -16,6 +16,9 @@ struct iio_channels_mask * iio_create_channels_mask(unsigned int nb_channels) struct iio_channels_mask *mask; size_t nb_words = (nb_channels + 31) / 32; + if (!nb_words) + return NULL; + mask = zalloc(sizeof(*mask) + nb_words * sizeof(uint32_t)); if (mask) mask->words = nb_words;