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

[PATCH] grep -An -Bm: fix invocation of external grep command

From
Junio C Hamano <gitster@pobox.com>
Date
Nov 18, 2007, 05:18 UTC
Message-ID
<7vk5ogxhbd.fsf@gitster.siamese.dyndns.org>

When building command line to invoke external grep, the arguments to -A/-B/-C options were placd in randarg[] buffer, but the code forgot that snprintf() does not count terminating NUL in its return value. This caused "git grep -A1 -B2" to invoke external grep with "-B21 -A1".

Signed-off-by: Junio C Hamano <gitster@pobox.com>
---
 * This bug was present since mid May, 2006.
 builtin-grep.c |    6 +++---
 1 files changed, 3 insertions(+), 3 deletions(-)
diff --git a/builtin-grep.c b/builtin-grep.c
index 185876b..bbf747f 100644
--- a/builtin-grep.c
+++ b/builtin-grep.c
@@ -294,7 +294,7 @@ static int external_grep(struct grep_opt *opt, const char
 			if (opt->pre_context) {
 				push_arg("-B");
 				len += snprintf(argptr, sizeof(randarg)-len,
-						"%u", opt->pre_context);
+						"%u", opt->pre_context) + 1;
 				if (sizeof(randarg) <= len)
 					die("maximum length of args exceeded");
 				push_arg(argptr);
@@ -303,7 +303,7 @@ static int external_grep(struct grep_opt *opt, const char
 			if (opt->post_context) {
 				push_arg("-A");
 				len += snprintf(argptr, sizeof(randarg)-len,
-						"%u", opt->post_context);
+						"%u", opt->post_context) + 1;
 				if (sizeof(randarg) <= len)
 					die("maximum length of args exceeded");
 				push_arg(argptr);
@@ -313,7 +313,7 @@ static int external_grep(struct grep_opt *opt, const char
 		else {
 			push_arg("-C");
 			len += snprintf(argptr, sizeof(randarg)-len,
-					"%u", opt->post_context);
+					"%u", opt->post_context) + 1;
 			if (sizeof(randarg) <= len)
 				die("maximum length of args exceeded");
 			push_arg(argptr);
Message 1 of 1 in “grep -An -Bm: fix invocation of external grep command”
  1. grep -An -Bm: fix invocation of external grep commandJunio C Hamano, Nov 18, 2007

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.