From d3b5b4b88c4d34bb0325fde0a6bf0a918ebfe55a Mon Sep 17 00:00:00 2001 From: Thomas Haller Date: Tue, 24 Oct 2023 11:57:08 +0200 Subject: gmputil: add nft_gmp_free() to free strings from mpz_get_str() mpz_get_str() (with NULL as first argument) will allocate a buffer using the allocator functions (mp_set_memory_functions()). We should free those buffers with the corresponding free function. Add nft_gmp_free() for that and use it. The name nft_gmp_free() is chosen because "mini-gmp.c" already has an internal define called gmp_free(). There wouldn't be a direct conflict, but using the same name is confusing. And maybe our own defines should have a clear nft prefix. Signed-off-by: Thomas Haller Signed-off-by: Pablo Neira Ayuso --- src/gmputil.c | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) (limited to 'src/gmputil.c') diff --git a/src/gmputil.c b/src/gmputil.c index cb26b558..b4529259 100644 --- a/src/gmputil.c +++ b/src/gmputil.c @@ -184,7 +184,7 @@ int mpz_vfprintf(FILE *fp, const char *f, va_list args) str = mpz_get_str(NULL, base, *value); ok = str && fwrite(str, 1, len, fp) == len; - free(str); + nft_gmp_free(str); if (!ok) return -1; @@ -196,3 +196,22 @@ int mpz_vfprintf(FILE *fp, const char *f, va_list args) return n; } #endif + +void nft_gmp_free(void *ptr) +{ + void (*free_fcn)(void *, size_t); + + /* When we get allocated memory from gmp, it was allocated via the + * allocator() from mp_set_memory_functions(). We should pair the free + * with the corresponding free function, which we get via + * mp_get_memory_functions(). + * + * It's not clear what the correct blk_size is. The default allocator + * function of gmp just wraps free() and ignores the extra argument. + * Assume 0 is fine. + */ + + mp_get_memory_functions(NULL, NULL, &free_fcn); + + (*free_fcn)(ptr, 0); +} -- cgit v1.2.3