From e53c2141b3e1e0438608573bf628584d02f394c5 Mon Sep 17 00:00:00 2001 From: Peter Hutterer Date: Wed, 22 Apr 2026 12:08:53 +1000 Subject: [PATCH] util: add a free_clear() helper to reset after free Same as e.g. g_clear_pointer(). Switch a number of obvious call sites over to use this, the rest will come over time. Part-of: --- src/libinput-plugin-lua.c | 3 +-- src/util-bits.h | 4 ++-- src/util-mem.h | 11 +++++++++++ src/util-stringbuf.h | 3 +-- tools/libinput-record.c | 3 +-- 5 files changed, 16 insertions(+), 8 deletions(-) diff --git a/src/libinput-plugin-lua.c b/src/libinput-plugin-lua.c index 1036b3f0..e7f6618e 100644 --- a/src/libinput-plugin-lua.c +++ b/src/libinput-plugin-lua.c @@ -375,8 +375,7 @@ remove_device(struct libinput_lua_plugin *plugin, EvdevDevice *evdev) list_for_each_safe(prop, &evdev->udev_properties_list, link) { udev_property_destroy(prop); } - free(evdev->name); - evdev->name = NULL; + free_clear(&evdev->name); evdev->device = libinput_device_unref(evdev->device); /* This device no longer exists but our lua code may have a diff --git a/src/util-bits.h b/src/util-bits.h index bf6a69f2..801dd3a3 100644 --- a/src/util-bits.h +++ b/src/util-bits.h @@ -36,6 +36,7 @@ #include #include "util-macros.h" +#include "util-mem.h" #define bit(x_) (1UL << (x_)) #define NBITS(b) (b * 8) @@ -281,8 +282,7 @@ infmask_new(void) _nonnull_(1) static inline void infmask_reset(infmask_t *mask) { - free(mask->mask); - mask->mask = NULL; + free_clear(&mask->mask); mask->nmasks = 0; } diff --git a/src/util-mem.h b/src/util-mem.h index 166ea82d..fe2522e6 100644 --- a/src/util-mem.h +++ b/src/util-mem.h @@ -186,3 +186,14 @@ steal_fd(int *fd) *fd = -1; return copy; } + +/** + * Frees the pointer content and resets the data to NULL. + */ +#define free_clear(ptr_) \ + do { \ + typeof((ptr_)) _pp = (ptr_); \ + typeof(*(ptr_)) _p = *_pp; \ + *_pp = NULL; \ + free(_p); \ + } while(0) diff --git a/src/util-stringbuf.h b/src/util-stringbuf.h index 7ab13383..5f545dbb 100644 --- a/src/util-stringbuf.h +++ b/src/util-stringbuf.h @@ -53,8 +53,7 @@ stringbuf_is_empty(struct stringbuf *b) static inline void stringbuf_reset(struct stringbuf *b) { - free(b->data); - b->data = NULL; + free_clear(&b->data); b->sz = 0; b->len = 0; } diff --git a/tools/libinput-record.c b/tools/libinput-record.c index a06b9c3f..d858f266 100644 --- a/tools/libinput-record.c +++ b/tools/libinput-record.c @@ -2372,8 +2372,7 @@ mainloop(struct record_context *ctx) } } } - free(ctx->output_file.name_with_suffix); - ctx->output_file.name_with_suffix = NULL; + free_clear(&ctx->output_file.name_with_suffix); } while (autorestart && !ctx->stop); sigprocmask(SIG_UNBLOCK, &mask, NULL);