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

2 messages, 2 authors, 2016-06-15 · open the first message on its own page

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

From: Andreas Schwab <hidden>
Date: 2016-06-15 22:55:46

René Scharfe [off-list ref] writes:
+	return '\0' - ent->name[key->len];
You need to cast to unsigned char first to make it consistent with
memcmp and strcmp.

Andreas.

-- 
Andreas Schwab, schwab@linux-m68k.org
GPG Key fingerprint = 58CA 54C7 6D53 942B 1756  01D3 44D5 214B 8276 4ED5
"And now for something completely different."

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

From: René Scharfe <hidden>
Date: 2016-06-15 22:55:47

Am 15.01.2013 21:27, schrieb Andreas Schwab:
René Scharfe [off-list ref] writes:
quoted
+	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 <redacted>
---
 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
Keyboard shortcuts
hback out one level
jnext message in thread
kprevious message in thread
ldrill in
Escclose help / fold thread tree
?toggle this help