// SPDX-FileCopyrightText: 2025 UnionTech Software Technology Co., Ltd.
//
// SPDX-License-Identifier: GPL-3.0-or-later

#ifndef CLEANUP_H
#define CLEANUP_H

#include <stdlib.h>

#ifdef __cplusplus
extern "C" {
#endif

/* Cleanup helpers for automatic memory management */
static inline void freep(void *p)
{
    free(*(void **)p);
}

/* Free a NULL-terminated string array
 * IMPORTANT: This function assumes the array is properly NULL-terminated
 * and stops at the first NULL element. To prevent memory leaks:
 * 1. Always initialize arrays with calloc() or set trailing elements to NULL
 * 2. When populating array elements, check allocation success before continuing
 * 3. If allocation fails mid-array, either return immediately or ensure
 *    subsequent elements remain NULL (as initialized by calloc)
 */
static inline void strv_freep(char ***p)
{
    if (*p) {
        for (char **s = *p; *s; s++)
            free(*s);
        free(*p);
    }
}

#define _cleanup_free_ __attribute__((cleanup(freep)))
#define _cleanup_strv_ __attribute__((cleanup(strv_freep)))

#ifdef __cplusplus
}
#endif

#endif // CLEANUP_H
