From 75e1778fac7841bb9477a2d845d810c9ea2ed4e8 Mon Sep 17 00:00:00 2001 From: Martin Pulec Date: Wed, 4 Jun 2025 12:30:08 +0200 Subject: [PATCH] macros/snprintf_ch: handle cert-err33-c warn Handle clang-tidy cert-err33-c warning that output of snprintf is not used. The return value should be used to handlet truncation - it is hard to handle this generically but we may issue at least a warning. --- src/utils/macros.h | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/utils/macros.h b/src/utils/macros.h index 0048a3b1f..3453efc4d 100644 --- a/src/utils/macros.h +++ b/src/utils/macros.h @@ -40,9 +40,11 @@ #ifdef __cplusplus #include +#include // for fprintf, stderr #include // for strchr, strncmp #else #include +#include // for fprintf, stderr #include // for strchr, strncmp #endif @@ -99,8 +101,19 @@ } \ } while (0) -/// shortcut for `snprintf(var, sizeof var...)`, `var` must be a char array -#define snprintf_ch(str, ...) snprintf(str, sizeof str, __VA_ARGS__) +/// shortcut for `snprintf(var, sizeof var...)`, `var` must be a char array; +/// truncation handled +#define snprintf_ch(str, ...) \ + do { /* NOLINT(cppcoreguidelines-avoid-do-while) */ \ + if (snprintf(str, sizeof str, __VA_ARGS__) >= \ + (int) sizeof str) { \ + fprintf(stderr, \ + "%s:%d: %s: snprintf truncates %s (%d B " \ + "needed)!\n", \ + __FILE__, __LINE__, __func__, #str, \ + snprintf(str, sizeof str, __VA_ARGS__)); \ + } \ + } while (0) #define STARTS_WITH(str, token) !strncmp(str, token, strlen(token)) /**