Skip to content

Commit ec93bba

Browse files
committed
macosx specific zmalloc.c, uses malloc_size function in order to avoid to waste memory and time to put an additional header
1 parent 333298d commit ec93bba

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

TODO

+2-1
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,8 @@ AFTER 1.0 stable release
2929
side the type also takes an hash table with key->score mapping, so that when
3030
there is an update we lookup the current score and can traverse the tree.
3131
* BITMAP type
32-
* LRANGE 4 0 should return the same elements as LRANGE 0 4 but in reverse order
32+
* LRANGE 4 0 should return the same elements as LRANGE 0 4 but in reverse order (only if we get enough motivated requests about it)
33+
* zmalloc() should avoid to add a private header for archs where there is some other kind of libc-specific way to get the size of a malloced block.
3334

3435
FUTURE HINTS
3536

zmalloc.c

+30
Original file line numberDiff line numberDiff line change
@@ -31,23 +31,45 @@
3131
#include <stdlib.h>
3232
#include <string.h>
3333

34+
#ifdef __APPLE__
35+
#include <malloc/malloc.h>
36+
#define HAVE_MALLOC_SIZE
37+
#define redis_malloc_size(p) malloc_size(p)
38+
#endif
39+
3440
static size_t used_memory = 0;
3541

3642
void *zmalloc(size_t size) {
3743
void *ptr = malloc(size+sizeof(size_t));
3844

3945
if (!ptr) return NULL;
46+
#ifdef HAVE_MALLOC_SIZE
47+
used_memory += redis_malloc_size(ptr);
48+
return ptr;
49+
#else
4050
*((size_t*)ptr) = size;
4151
used_memory += size+sizeof(size_t);
4252
return (char*)ptr+sizeof(size_t);
53+
#endif
4354
}
4455

4556
void *zrealloc(void *ptr, size_t size) {
57+
#ifndef HAVE_MALLOC_SIZE
4658
void *realptr;
59+
#endif
4760
size_t oldsize;
4861
void *newptr;
4962

5063
if (ptr == NULL) return zmalloc(size);
64+
#ifdef HAVE_MALLOC_SIZE
65+
oldsize = redis_malloc_size(ptr);
66+
newptr = realloc(ptr,size);
67+
if (!newptr) return NULL;
68+
69+
used_memory -= oldsize;
70+
used_memory += redis_malloc_size(newptr);
71+
return newptr;
72+
#else
5173
realptr = (char*)ptr-sizeof(size_t);
5274
oldsize = *((size_t*)realptr);
5375
newptr = realloc(realptr,size+sizeof(size_t));
@@ -57,17 +79,25 @@ void *zrealloc(void *ptr, size_t size) {
5779
used_memory -= oldsize;
5880
used_memory += size;
5981
return (char*)newptr+sizeof(size_t);
82+
#endif
6083
}
6184

6285
void zfree(void *ptr) {
86+
#ifndef HAVE_MALLOC_SIZE
6387
void *realptr;
6488
size_t oldsize;
89+
#endif
6590

6691
if (ptr == NULL) return;
92+
#ifdef HAVE_MALLOC_SIZE
93+
used_memory -= redis_malloc_size(ptr);
94+
free(ptr);
95+
#else
6796
realptr = (char*)ptr-sizeof(size_t);
6897
oldsize = *((size_t*)realptr);
6998
used_memory -= oldsize+sizeof(size_t);
7099
free(realptr);
100+
#endif
71101
}
72102

73103
char *zstrdup(const char *s) {

0 commit comments

Comments
 (0)