Patchwork [2,of,3,V2] chg: use mallocx and reallocx in hgclient

login
register
mail settings
Submitter Jun Wu
Date Feb. 17, 2016, 3:08 p.m.
Message ID <a87f14c869a38406eab0.1455721738@x1c>
Download mbox | patch
Permalink /patch/13239/
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 1455721689 0
#      Wed Feb 17 15:08:09 2016 +0000
# Node ID a87f14c869a38406eab0595b514b915e6b6391a6
# Parent  5ecfc2796fdb4314791139aece42d11d9d24fe0f
chg: use mallocx and reallocx in hgclient

This patch simplifies the code a bit, reduces the binary size a little, and
makes chg pass clang-analyzer. Previously we forgot to check a malloc result
in initcontext.
Jun Wu - Feb. 17, 2016, 6:58 p.m.
I found I was wrong, so was the stupid clang-analyzer.
Amend the commit message and "ctx->maxdatasize = ..." line please.

On 02/17/2016 03:08 PM, Jun Wu wrote:
> -	ctx->data = malloc(defaultdatasize);
> +	ctx->data = mallocx(defaultdatasize);
 > 	ctx->maxdatasize = (ctx->data) ? defaultdatasize : 0;

Patch

diff --git a/contrib/chg/hgclient.c b/contrib/chg/hgclient.c
--- a/contrib/chg/hgclient.c
+++ b/contrib/chg/hgclient.c
@@ -71,7 +71,7 @@ 
 static void initcontext(context_t *ctx)
 {
 	ctx->ch = '\0';
-	ctx->data = malloc(defaultdatasize);
+	ctx->data = mallocx(defaultdatasize);
 	ctx->maxdatasize = (ctx->data) ? defaultdatasize : 0;
 	ctx->datasize = 0;
 	debugmsg("initialize context buffer with size %zu", ctx->maxdatasize);
@@ -84,10 +84,7 @@ 
 
 	newsize = defaultdatasize
 		* ((newsize + defaultdatasize - 1) / defaultdatasize);
-	char *p = realloc(ctx->data, newsize);
-	if (!p)
-		abortmsg("failed to allocate buffer");
-	ctx->data = p;
+	ctx->data = reallocx(ctx->data, newsize);
 	ctx->maxdatasize = newsize;
 	debugmsg("enlarge context buffer to %zu", ctx->maxdatasize);
 }
@@ -195,9 +192,7 @@ 
 	for (;;) {
 		if (nargs + 1 >= maxnargs) {  /* including last NULL */
 			maxnargs += 256;
-			args = realloc(args, maxnargs * sizeof(args[0]));
-			if (!args)
-				abortmsg("failed to allocate args buffer");
+			args = reallocx(args, maxnargs * sizeof(args[0]));
 		}
 		args[nargs] = s;
 		nargs++;
@@ -432,9 +427,7 @@ 
 			 addr.sun_path, errno);
 	}
 
-	hgclient_t *hgc = malloc(sizeof(hgclient_t));
-	if (!hgc)
-		abortmsg("failed to allocate hgclient object");
+	hgclient_t *hgc = mallocx(sizeof(hgclient_t));
 	memset(hgc, 0, sizeof(*hgc));
 	hgc->sockfd = fd;
 	initcontext(&hgc->ctx);