summaryrefslogtreecommitdiff
path: root/src/zmalloc.c
diff options
context:
space:
mode:
authorantirez <antirez@gmail.com>2012-08-24 12:55:37 +0200
committerantirez <antirez@gmail.com>2012-08-24 12:55:37 +0200
commit6fdc635447b1a5dd0a4f7b13c15fdd6c108dabee (patch)
treeb8db5f26496115d56fc4e05fee0b3c20a38919c8 /src/zmalloc.c
parent850789ce73dbb236591692708437e1bd705dbce3 (diff)
downloadredis-6fdc635447b1a5dd0a4f7b13c15fdd6c108dabee.tar.gz
Better Out of Memory handling.
The previous implementation of zmalloc.c was not able to handle out of memory in an application-specific way. It just logged an error on standard error, and aborted. The result was that in the case of an actual out of memory in Redis where malloc returned NULL (In Linux this actually happens under specific overcommit policy settings and/or with no or little swap configured) the error was not properly logged in the Redis log. This commit fixes this problem, fixing issue #509. Now the out of memory is properly reported in the Redis log and a stack trace is generated. The approach used is to provide a configurable out of memory handler to zmalloc (otherwise the default one logging the event on the standard output is used).
Diffstat (limited to 'src/zmalloc.c')
-rw-r--r--src/zmalloc.c14
1 files changed, 10 insertions, 4 deletions
diff --git a/src/zmalloc.c b/src/zmalloc.c
index 79b561586..afa9fda80 100644
--- a/src/zmalloc.c
+++ b/src/zmalloc.c
@@ -109,17 +109,19 @@ static size_t used_memory = 0;
static int zmalloc_thread_safe = 0;
pthread_mutex_t used_memory_mutex = PTHREAD_MUTEX_INITIALIZER;
-static void zmalloc_oom(size_t size) {
+static void zmalloc_default_oom(size_t size) {
fprintf(stderr, "zmalloc: Out of memory trying to allocate %zu bytes\n",
size);
fflush(stderr);
abort();
}
+static void (*zmalloc_oom_handler)(size_t) = zmalloc_default_oom;
+
void *zmalloc(size_t size) {
void *ptr = malloc(size+PREFIX_SIZE);
- if (!ptr) zmalloc_oom(size);
+ if (!ptr) zmalloc_oom_handler(size);
#ifdef HAVE_MALLOC_SIZE
update_zmalloc_stat_alloc(zmalloc_size(ptr),size);
return ptr;
@@ -133,7 +135,7 @@ void *zmalloc(size_t size) {
void *zcalloc(size_t size) {
void *ptr = calloc(1, size+PREFIX_SIZE);
- if (!ptr) zmalloc_oom(size);
+ if (!ptr) zmalloc_oom_handler(size);
#ifdef HAVE_MALLOC_SIZE
update_zmalloc_stat_alloc(zmalloc_size(ptr),size);
return ptr;
@@ -155,7 +157,7 @@ void *zrealloc(void *ptr, size_t size) {
#ifdef HAVE_MALLOC_SIZE
oldsize = zmalloc_size(ptr);
newptr = realloc(ptr,size);
- if (!newptr) zmalloc_oom(size);
+ if (!newptr) zmalloc_oom_handler(size);
update_zmalloc_stat_free(oldsize);
update_zmalloc_stat_alloc(zmalloc_size(newptr),size);
@@ -236,6 +238,10 @@ void zmalloc_enable_thread_safeness(void) {
zmalloc_thread_safe = 1;
}
+void zmalloc_set_oom_handler(void (*oom_handler)(size_t)) {
+ zmalloc_oom_handler = oom_handler;
+}
+
/* Get the RSS information in an OS-specific way.
*
* WARNING: the function zmalloc_get_rss() is not designed to be fast