From 779bf7658e3fac6f5a4da533323331b8a9d47201 Mon Sep 17 00:00:00 2001
From: Marek Vavrusa <marek.vavrusa@nic.cz>
Date: Fri, 14 Dec 2012 14:53:22 +0100
Subject: [PATCH] Implemented xmalloc()/xrealloc() memory patterns.

The idea is to die gracefully if memory allocation fails.
Could revert this behavior later on.
---
 src/common/mempattern.c | 22 ++++++++++++++++++++++
 src/common/mempattern.h |  6 ++++++
 2 files changed, 28 insertions(+)

diff --git a/src/common/mempattern.c b/src/common/mempattern.c
index acf6eac2f..df9e1b93a 100644
--- a/src/common/mempattern.c
+++ b/src/common/mempattern.c
@@ -21,8 +21,30 @@
 #include <config.h>
 #include <stdarg.h>
 
+#include "common/log.h"
 #include "common/slab/alloc-common.h"
 
+void* xmalloc(size_t l)
+{
+	void *p = malloc(l);
+	if (p == NULL) {
+		log_server_fatal("Failed to allocate %zu bytes.\n", l);
+		abort();
+	}
+	return p;
+}
+
+void *xrealloc(void *p, size_t l)
+{
+	p = realloc(p, l);
+	if (p == NULL) {
+		log_server_fatal("Failed to reallocate to %zu bytes from %p.\n",
+		                 l, p);
+		abort();
+	}
+	return p;
+}
+
 
 int mreserve(char **p, size_t tlen, size_t min, size_t allow, size_t *reserved)
 {
diff --git a/src/common/mempattern.h b/src/common/mempattern.h
index ebfe4aeb0..cd19cf241 100644
--- a/src/common/mempattern.h
+++ b/src/common/mempattern.h
@@ -27,6 +27,12 @@
 #ifndef _KNOTD_COMMON_MALLOC_H_
 #define _KNOTD_COMMON_MALLOC_H_
 
+/*! \brief Allocate memory or die. */
+void* xmalloc(size_t l);
+
+/*! \brief Reallocate memory or die. */
+void *xrealloc(void *p, size_t l);
+
 /*!
  * \brief Reserve new or trim excessive memory.
  *
-- 
GitLab