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

Re: [RFC/PATCH] ignore memcmp() overreading in bsearch() callback

From
René Scharfe <rene.scharfe@lsrfire.ath.cx>
Date
Jan 16, 2013, 01:08 UTC
Message-ID
<50F5FD80.1000808@lsrfire.ath.cx>
In-Reply-To
<m2libunqdj.fsf@igel.home>
Am 15.01.2013 21:27, schrieb Andreas Schwab:
Show 6 quoted lines
> René Scharfe <rene.scharfe@lsrfire.ath.cx> writes:
> 
>> +	return '\0' - ent->name[key->len];
> 
> You need to cast to unsigned char first to make it consistent with
> memcmp and strcmp.
Thanks for catching this!
-- >8 --
Subject: [PATCH] refs: use strncmp() instead of strlen() and memcmp()

Simplify ref_entry_cmp_sslice() by using strncmp() to compare the length-limited key and a NUL-terminated entry. While we're at it, retain the const attribute of the input pointers.

Signed-off-by: Rene Scharfe <rene.scharfe@lsrfire.ath.cx>
---
 refs.c | 10 ++++------
 1 file changed, 4 insertions(+), 6 deletions(-)
diff --git a/refs.c b/refs.c
index 541fec2..5129da0 100644
--- a/refs.c
+++ b/refs.c
@@ -333,14 +333,12 @@ struct string_slice {
 
 static int ref_entry_cmp_sslice(const void *key_, const void *ent_)
 {
-	struct string_slice *key = (struct string_slice *)key_;
-	struct ref_entry *ent = *(struct ref_entry **)ent_;
-	int entlen = strlen(ent->name);
-	int cmplen = key->len < entlen ? key->len : entlen;
-	int cmp = memcmp(key->str, ent->name, cmplen);
+	const struct string_slice *key = key_;
+	const struct ref_entry *ent = *(const struct ref_entry * const *)ent_;
+	int cmp = strncmp(key->str, ent->name, key->len);
 	if (cmp)
 		return cmp;
-	return key->len - entlen;
+	return '\0' - (unsigned char)ent->name[key->len];
 }
 
 /*
-- 
1.8.0
Previous: Andreas Schwab
Message 9 of 9 in “ignore memcmp() overreading in bsearch() callback”
  1. ignore memcmp() overreading in bsearch() callbackJunio C Hamano, Jan 14, 2013
  2. Johannes SchindelinJan 14, 2013
  3. Junio C HamanoJan 15, 2013
  4. Jeff KingJan 15, 2013
  5. Junio C HamanoJan 15, 2013
  6. Jeff KingJan 15, 2013
  7. René ScharfeJan 15, 2013
  8. Andreas SchwabJan 15, 2013
  9. René ScharfeJan 16, 2013

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.