git/list[1] front-page[2] threads[3] people[4] search[5] about
 

[PATCHv2 2/2] builtin/commit.c: drop use snprintf via dynamic allocation

From
Elia Pinto <gitter.spiros@gmail.com>
Date
Jan 11, 2017, 07:10 UTC
Message-ID
<20170111071032.27797-2-gitter.spiros@gmail.com>
In-Reply-To
<20170111071032.27797-1-gitter.spiros@gmail.com>

In general snprintf is bad because it may silently truncate results if we're wrong. In this patch, instead of using xnprintf, which asserts that we don't truncate, we are switching to dynamic allocation, so we can avoid dealing with magic numbers in the code.

Helped-by: Jeff King <peff@peff.net> 
Signed-off-by: Elia Pinto <gitter.spiros@gmail.com>
---
This is the second version of the patch.

I have split the original commit in two, as discussed here http://public-inbox.org/git/20161213132717.42965-1-gitter.spiros@gmail.com/.

 builtin/commit.c | 10 ++++------
 1 file changed, 4 insertions(+), 6 deletions(-)
diff --git a/builtin/commit.c b/builtin/commit.c
index 09bcc0f13..37228330c 100644
--- a/builtin/commit.c
+++ b/builtin/commit.c
@@ -1526,12 +1526,10 @@ static int git_commit_config(const char *k, const char *v, void *cb)
 static int run_rewrite_hook(const unsigned char *oldsha1,
 			    const unsigned char *newsha1)
 {
-	/* oldsha1 SP newsha1 LF NUL */
-	static char buf[2*40 + 3];
+	char *buf;
 	struct child_process proc = CHILD_PROCESS_INIT;
 	const char *argv[3];
 	int code;
-	size_t n;
 
 	argv[0] = find_hook("post-rewrite");
 	if (!argv[0])
@@ -1547,11 +1545,11 @@ static int run_rewrite_hook(const unsigned char *oldsha1,
 	code = start_command(&proc);
 	if (code)
 		return code;
-	n = snprintf(buf, sizeof(buf), "%s %s\n",
-		     sha1_to_hex(oldsha1), sha1_to_hex(newsha1));
+	buf = xstrfmt("%s %s\n", sha1_to_hex(oldsha1), sha1_to_hex(newsha1));
 	sigchain_push(SIGPIPE, SIG_IGN);
-	write_in_full(proc.in, buf, n);
+	write_in_full(proc.in, buf, strlen(buf));
 	close(proc.in);
+	free(buf);
 	sigchain_pop(SIGPIPE);
 	return finish_command(&proc);
 }
-- 
2.11.0.154.g5f5f154
Previous: Elia PintoNext: Junio C Hamano
Message 2 of 3 in “[PATCHv2 1/2] builtin/commit.c: drop use snprintf via dynamic allocation”
  1. Elia PintoJan 11, 2017
  2. 2/2 builtin/commit.c: drop use snprintf via dynamic allocationElia Pinto, Jan 11, 2017
  3. Junio C HamanoJan 11, 2017

Read the whole thread, see it on lore, or plain text.

$ cat FOOTERMessages come from the public archive at lore.kernel.org/git, fetched every hour. The front page is chosen and written each morning by an AI editor and can be wrong; the threads themselves are the record. About and API. For agents: an MCP server at https://gitlist.dev/mcp, and any thread, story or person page as Markdown by adding .md to its URL (or sending Accept: text/markdown). Details in /llms.txt.