From 96fcc6089e25f4c0532cd134eaa0bde906e9e931 Mon Sep 17 00:00:00 2001 From: Yuxuan Shui Date: Sat, 16 Jul 2022 14:17:11 +0100 Subject: [PATCH] c2: silence a compiler warning GCC warns about a use after free, because a pointer is used in pointer comparison after it was freed. This particular case is completely safe, but GCC warns anyway. Move the free after the comparison requires me duplicating the free a couple of times, so instead I made use of the cleanup attribute to auto free the pointer when it goes out of scope. Signed-off-by: Yuxuan Shui --- src/c2.c | 3 +-- src/compiler.h | 6 ++++++ src/utils.h | 9 +++++++++ 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/c2.c b/src/c2.c index d0c1aeb..70d5b84 100644 --- a/src/c2.c +++ b/src/c2.c @@ -886,11 +886,10 @@ static int c2_parse_pattern(const char *pattern, int offset, c2_ptr_t *presult) case 'v': *(ptptnstr++) = '\v'; break; case 'o': case 'x': { - char *tstr = strndup(pattern + offset + 1, 2); + scoped_charp tstr = strndup(pattern + offset + 1, 2); char *pstr = NULL; long val = strtol( tstr, &pstr, ('o' == pattern[offset] ? 8 : 16)); - free(tstr); if (pstr != &tstr[2] || val <= 0) c2_error("Invalid octal/hex escape " "sequence."); diff --git a/src/compiler.h b/src/compiler.h index f146bd2..7632670 100644 --- a/src/compiler.h +++ b/src/compiler.h @@ -85,6 +85,12 @@ # define fallthrough() #endif +#if __has_attribute(cleanup) +# define cleanup(func) __attribute__((cleanup(func))) +#else +# error "Compiler is missing cleanup attribute" +#endif + #if __STDC_VERSION__ >= 201112L # define attr_noret _Noreturn #else diff --git a/src/utils.h b/src/utils.h index 23a5abb..b9a81b4 100644 --- a/src/utils.h +++ b/src/utils.h @@ -273,6 +273,15 @@ allocchk_(const char *func_name, const char *file, unsigned int line, void *ptr) void name##_ref(type *a); \ void name##_unref(type **a); +static inline void free_charpp(char **str) { + if (str) { + free(*str); + *str = NULL; + } +} + +/// An allocated char* that is automatically freed when it goes out of scope. +#define scoped_charp char *cleanup(free_charpp) /// /// Calculates next closest power of two of 32bit integer n