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: <https://gitlab.freedesktop.org/libinput/libinput/-/merge_requests/1472>
This commit is contained in:
Peter Hutterer 2026-04-22 12:08:53 +10:00 committed by Marge Bot
parent c2c8414605
commit e53c2141b3
5 changed files with 16 additions and 8 deletions

View file

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

View file

@ -36,6 +36,7 @@
#include <stdlib.h>
#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;
}

View file

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

View file

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

View file

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