From: Willy Tarreau Date: Fri, 22 Oct 2021 14:33:53 +0000 (+0200) Subject: MINOR: memprof: add one pointer size to the size of allocations X-Git-Tag: v2.5-dev11~6 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=1de51eb7279fb4257bdb3816c5e9a7990b7ae211;p=thirdparty%2Fhaproxy.git MINOR: memprof: add one pointer size to the size of allocations The current model causes an issue when trying to spot memory leaks, because malloc(0) or realloc(0) do not count as allocations since we only account for the application-usable size. This is the problem that made issue #1406 not to appear as a leak. What we're doing now is to account for one extra pointer (the one that memory allocators usually place before the returned area), so that a malloc(0) will properly account for 4 or 8 bytes. We don't need something exact, we just need something non-zero so that a realloc(X) followed by a realloc(0) without a free() gives a small non-zero result. It was verified that the results are stable including in the presence of lots of malloc/realloc/free as happens when stressing Lua. It would make sense to backport this to 2.4 as it helps in bug reports. --- diff --git a/src/activity.c b/src/activity.c index 0046f3aead..aab0b3c2b9 100644 --- a/src/activity.c +++ b/src/activity.c @@ -241,7 +241,7 @@ void *malloc(size_t size) return memprof_malloc_handler(size); ret = memprof_malloc_handler(size); - size = malloc_usable_size(ret); + size = malloc_usable_size(ret) + sizeof(void *); bin = memprof_get_bin(__builtin_return_address(0), MEMPROF_METH_MALLOC); _HA_ATOMIC_ADD(&bin->alloc_calls, 1); @@ -266,7 +266,7 @@ void *calloc(size_t nmemb, size_t size) return memprof_calloc_handler(nmemb, size); ret = memprof_calloc_handler(nmemb, size); - size = malloc_usable_size(ret); + size = malloc_usable_size(ret) + sizeof(void *); bin = memprof_get_bin(__builtin_return_address(0), MEMPROF_METH_CALLOC); _HA_ATOMIC_ADD(&bin->alloc_calls, 1); @@ -297,6 +297,10 @@ void *realloc(void *ptr, size_t size) ret = memprof_realloc_handler(ptr, size); size = malloc_usable_size(ret); + /* only count the extra link for new allocations */ + if (!ptr) + size += sizeof(void *); + bin = memprof_get_bin(__builtin_return_address(0), MEMPROF_METH_REALLOC); if (size > size_before) { _HA_ATOMIC_ADD(&bin->alloc_calls, 1); @@ -329,7 +333,7 @@ void free(void *ptr) return; } - size_before = malloc_usable_size(ptr); + size_before = malloc_usable_size(ptr) + sizeof(void *); memprof_free_handler(ptr); bin = memprof_get_bin(__builtin_return_address(0), MEMPROF_METH_FREE);