[hackers] [sbase][PATCH] grep: Minor stylistic changes

From: Santtu Lakkala <inz_AT_inz.fi>
Date: Fri, 7 Nov 2025 12:22:02 +0200

Use a flexible array member for pattern string to simplify addpattern()

Remove two redundant length checks; both already checked in loop
conditional.
---
 grep.c | 19 ++++++++-----------
 1 file changed, 8 insertions(+), 11 deletions(-)
diff --git a/grep.c b/grep.c
index 397f649..8ca6d51 100644
--- a/grep.c
+++ b/grep.c
_AT_@ -29,9 +29,9 @@ static int many;
 static int mode;
 
 struct pattern {
-	char *pattern;
 	regex_t preg;
 	SLIST_ENTRY(pattern) entry;
+	char pattern[];
 };
 
 static SLIST_HEAD(phead, pattern) phead;
_AT_@ -40,26 +40,23 @@ static void
 addpattern(const char *pattern)
 {
 	struct pattern *pnode;
-	char *tmp;
 	size_t patlen;
 
 	patlen = strlen(pattern);
 
+	pnode = enmalloc(Error, sizeof(*pnode) + patlen + 9);
+	SLIST_INSERT_HEAD(&phead, pnode, entry);
+
 	if (Fflag || (!xflag && !wflag)) {
-		tmp = enstrdup(Error, pattern);
+		memcpy(pnode->pattern, pattern, patlen + 1);
 	} else {
-		tmp = enmalloc(Error, patlen + 9);
-		sprintf(tmp, "%s%s%s%s%s",
+		sprintf(pnode->pattern, "%s%s%s%s%s",
 			xflag ? "^" : "\\<",
 			Eflag ? "(" : "\\(",
 			pattern,
 			Eflag ? ")" : "\\)",
 			xflag ? "$" : "\\>");
 	}
-
-	pnode = enmalloc(Error, sizeof(*pnode));
-	pnode->pattern = tmp;
-	SLIST_INSERT_HEAD(&phead, pnode, entry);
 }
 
 static void
_AT_@ -70,7 +67,7 @@ addpatternfile(FILE *fp)
 	ssize_t len = 0;
 
 	while ((len = getline(&buf, &size, fp)) > 0) {
-		if (len > 0 && buf[len - 1] == '\n')
+		if (buf[len - 1] == '\n')
 			buf[len - 1] = '\0';
 		addpattern(buf);
 	}
_AT_@ -90,7 +87,7 @@ grep(FILE *fp, const char *str)
 
 	for (n = 1; (len = getline(&buf, &size, fp)) > 0; n++) {
 		/* Remove the trailing newline if one is present. */
-		if (len && buf[len - 1] == '\n')
+		if (buf[len - 1] == '\n')
 			buf[len - 1] = '\0';
 		match = 0;
 		SLIST_FOREACH(pnode, &phead, entry) {
-- 
2.42.0
Received on Fri Nov 07 2025 - 11:22:02 CET

This archive was generated by hypermail 2.3.0 : Fri Nov 07 2025 - 11:24:36 CET