summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorguybe7 <guy.benoish@redislabs.com>2022-04-10 10:43:59 +0200
committerGitHub <noreply@github.com>2022-04-10 11:43:59 +0300
commiteeb0f1426c3a32c4278136bbbf24118c787f8714 (patch)
treee66cb9a068f4bd8ccee142a03f298686342bb585 /src
parent719db14ec78d9da1c8abe3577cb77019c4c61eb3 (diff)
downloadredis-eeb0f1426c3a32c4278136bbbf24118c787f8714.tar.gz
Add RM_TryAlloc (#10541)
Similarly to LCS, some modules would want to try to allocate memory, and fail gracefully if the allocation fails
Diffstat (limited to 'src')
-rw-r--r--src/module.c10
-rw-r--r--src/redismodule.h2
2 files changed, 11 insertions, 1 deletions
diff --git a/src/module.c b/src/module.c
index c4ec3f727..dd4612d08 100644
--- a/src/module.c
+++ b/src/module.c
@@ -464,11 +464,18 @@ static int moduleConvertArgFlags(int flags);
/* Use like malloc(). Memory allocated with this function is reported in
* Redis INFO memory, used for keys eviction according to maxmemory settings
* and in general is taken into account as memory allocated by Redis.
- * You should avoid using malloc(). */
+ * You should avoid using malloc().
+ * This function panics if unable to allocate enough memory. */
void *RM_Alloc(size_t bytes) {
return zmalloc(bytes);
}
+/* Similar to RM_Alloc, but returns NULL in case of allocation failure, instead
+ * of panicking. */
+void *RM_TryAlloc(size_t bytes) {
+ return ztrymalloc(bytes);
+}
+
/* Use like calloc(). Memory allocated with this function is reported in
* Redis INFO memory, used for keys eviction according to maxmemory settings
* and in general is taken into account as memory allocated by Redis.
@@ -12241,6 +12248,7 @@ void moduleRegisterCoreAPI(void) {
server.moduleapi = dictCreate(&moduleAPIDictType);
server.sharedapi = dictCreate(&moduleAPIDictType);
REGISTER_API(Alloc);
+ REGISTER_API(TryAlloc);
REGISTER_API(Calloc);
REGISTER_API(Realloc);
REGISTER_API(Free);
diff --git a/src/redismodule.h b/src/redismodule.h
index f27c06b0e..300a7e541 100644
--- a/src/redismodule.h
+++ b/src/redismodule.h
@@ -861,6 +861,7 @@ typedef struct RedisModuleTypeMethods {
#endif
REDISMODULE_API void * (*RedisModule_Alloc)(size_t bytes) REDISMODULE_ATTR;
+REDISMODULE_API void * (*RedisModule_TryAlloc)(size_t bytes) REDISMODULE_ATTR;
REDISMODULE_API void * (*RedisModule_Realloc)(void *ptr, size_t bytes) REDISMODULE_ATTR;
REDISMODULE_API void (*RedisModule_Free)(void *ptr) REDISMODULE_ATTR;
REDISMODULE_API void * (*RedisModule_Calloc)(size_t nmemb, size_t size) REDISMODULE_ATTR;
@@ -1191,6 +1192,7 @@ static int RedisModule_Init(RedisModuleCtx *ctx, const char *name, int ver, int
void *getapifuncptr = ((void**)ctx)[0];
RedisModule_GetApi = (int (*)(const char *, void *)) (unsigned long)getapifuncptr;
REDISMODULE_GET_API(Alloc);
+ REDISMODULE_GET_API(TryAlloc);
REDISMODULE_GET_API(Calloc);
REDISMODULE_GET_API(Free);
REDISMODULE_GET_API(Realloc);