From 8fd1031b10dec256d5b365b278815f9d8444e601 Mon Sep 17 00:00:00 2001 From: Bruce Merry Date: Sun, 30 Sep 2018 11:49:03 +0200 Subject: [PATCH] Fix incorrect memory usage accounting in zrealloc When HAVE_MALLOC_SIZE is false, each call to zrealloc causes used_memory to increase by PREFIX_SIZE more than it should, due to mis-matched accounting between the original zmalloc (which includes PREFIX size in its increment) and zrealloc (which misses it from its decrement). I've also supplied a command-line test to easily demonstrate the problem. It's not wired into the test framework, because I don't know TCL so I'm not sure how to automate it. --- src/server.c | 2 ++ src/zmalloc.c | 18 +++++++++++++++++- src/zmalloc.h | 4 ++++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/server.c b/src/server.c index 239434a2..bc4ae19e 100644 --- a/src/server.c +++ b/src/server.c @@ -4015,6 +4015,8 @@ int main(int argc, char **argv) { return endianconvTest(argc, argv); } else if (!strcasecmp(argv[2], "crc64")) { return crc64Test(argc, argv); + } else if (!strcasecmp(argv[2], "zmalloc")) { + return zmalloc_test(argc, argv); } return -1; /* test not found */ diff --git a/src/zmalloc.c b/src/zmalloc.c index 308774d8..2482f512 100644 --- a/src/zmalloc.c +++ b/src/zmalloc.c @@ -164,7 +164,7 @@ void *zrealloc(void *ptr, size_t size) { if (!newptr) zmalloc_oom_handler(size); *((size_t*)newptr) = size; - update_zmalloc_stat_free(oldsize); + update_zmalloc_stat_free(oldsize+PREFIX_SIZE); update_zmalloc_stat_alloc(size+PREFIX_SIZE); return (char*)newptr+PREFIX_SIZE; #endif @@ -438,4 +438,20 @@ size_t zmalloc_get_memory_size(void) { #endif } +#ifdef REDIS_TEST +#define UNUSED(x) ((void)(x)) +int zmalloc_test(int argc, char **argv) { + void *ptr; + UNUSED(argc); + UNUSED(argv); + printf("Initial used memory: %zu\n", zmalloc_used_memory()); + ptr = zmalloc(123); + printf("Allocated 123 bytes; used: %zu\n", zmalloc_used_memory()); + ptr = zrealloc(ptr, 456); + printf("Reallocated to 456 bytes; used: %zu\n", zmalloc_used_memory()); + zfree(ptr); + printf("Freed pointer; used: %zu\n", zmalloc_used_memory()); + return 0; +} +#endif diff --git a/src/zmalloc.h b/src/zmalloc.h index 9c922990..6fb19b04 100644 --- a/src/zmalloc.h +++ b/src/zmalloc.h @@ -103,4 +103,8 @@ size_t zmalloc_usable(void *ptr); #define zmalloc_usable(p) zmalloc_size(p) #endif +#ifdef REDIS_TEST +int zmalloc_test(int argc, char **argv); +#endif + #endif /* __ZMALLOC_H */