Patchwork [1,of,3,V2] chg: add utility functions mallocx, reallocx

login
register
mail settings
Submitter Jun Wu
Date Feb. 17, 2016, 3:08 p.m.
Message ID <5ecfc2796fdb43147911.1455721737@x1c>
Download mbox | patch
Permalink /patch/13241/
State Accepted
Delegated to: Yuya Nishihara
Headers show

Comments

Jun Wu - Feb. 17, 2016, 3:08 p.m.
# HG changeset patch
# User Jun Wu <quark@fb.com>
# Date 1455720698 0
#      Wed Feb 17 14:51:38 2016 +0000
# Node ID 5ecfc2796fdb4314791139aece42d11d9d24fe0f
# Parent  95bf01b8754016200a99fd3538e78030b2028c60
chg: add utility functions mallocx, reallocx

They are like malloc and realloc but will abort the program on error.
A lot of places use {m,re}alloc and check their results. This patch
can simplify them.

Patch

diff --git a/contrib/chg/util.c b/contrib/chg/util.c
--- a/contrib/chg/util.c
+++ b/contrib/chg/util.c
@@ -50,6 +50,20 @@ 
 	va_end(args);
 }
 
+void *mallocx(size_t size)
+{
+	void *result = malloc(size);
+	if (!result) abortmsg("failed to malloc");
+	return result;
+}
+
+void *reallocx(void *ptr, size_t size)
+{
+	void *result = realloc(ptr, size);
+	if (!result) abortmsg("failed to realloc");
+	return result;
+}
+
 /*
  * Execute a shell command in mostly the same manner as system(), with the
  * give environment variables, after chdir to the given cwd. Returns a status
diff --git a/contrib/chg/util.h b/contrib/chg/util.h
--- a/contrib/chg/util.h
+++ b/contrib/chg/util.h
@@ -19,6 +19,9 @@ 
 void enabledebugmsg(void);
 void debugmsg(const char *fmt, ...) PRINTF_FORMAT_;
 
+void *mallocx(size_t size);
+void *reallocx(void *ptr, size_t size);
+
 int runshellcmd(const char *cmd, const char *envp[], const char *cwd);
 
 #endif  /* UTIL_H_ */