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 <yshuiv7@gmail.com>
This commit is contained in:
Yuxuan Shui 2022-07-16 14:17:11 +01:00
parent 60c9695394
commit 96fcc6089e
No known key found for this signature in database
GPG Key ID: D3A4405BE6CC17F4
3 changed files with 16 additions and 2 deletions

View File

@ -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.");

View File

@ -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

View File

@ -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