[PATCH] avoid theoretical integer overflow and -Wsign-compare warning

Jim Meyering jim at meyering.net
Fri May 6 13:46:46 UTC 2011


Normally, even with --enable-gcc-warnings, I suppress warnings
from gcc's -Wsign-compare, but "make rpm" enables them, so in
preparing for the upcoming release I saw one of them:

    meta.cpp: In member function 'int AttrList::Next(const char**, const char**)':
    meta.cpp:629:24: warning: comparison between signed and unsigned integer \
      expressions [-Wsign-compare]

Looking at the code, I saw it'd be easy to avoid by an
otherwise-desirable int->size_t type change, and also
added the test to avoid even the slightest possibility of
integer overflow:

>From 8ace2b9ed42d91ce96f358103cf1b3d94f613fd9 Mon Sep 17 00:00:00 2001
From: Jim Meyering <meyering at redhat.com>
Date: Fri, 6 May 2011 14:47:35 +0200
Subject: [PATCH] avoid theoretical integer overflow and -Wsign-compare
 warning

* meta.cpp (class AttrList) [idx]: Change type: s/int/size_t/,
This variable is only ever incremented and used as a vector index.
---
 meta.cpp |    9 +++++++--
 1 files changed, 7 insertions(+), 2 deletions(-)

diff --git a/meta.cpp b/meta.cpp
index 3cf6f57..b88b8c3 100644
--- a/meta.cpp
+++ b/meta.cpp
@@ -611,7 +611,7 @@ public:
 	int			Next		(const char **, const char **);
         BSONObj                 obj;
 	vector<BSONElement>	vec;
-	int			idx;
+	size_t			idx;
 };

 AttrList::AttrList (BSONObj &bo)
@@ -627,7 +627,12 @@ AttrList::Next (const char **name, const char **value)
 	BSONElement	elem;

 	while (idx < vec.size()) {
-		elem = vec[idx++];
+		elem = vec[idx];
+
+		// Do not wrap back to 0 when vec.size is SIZE_MAX.
+		if (idx != vec.size())
+			idx++;
+
 		if (elem.type() == String) {
 			*name = elem.fieldName();
 			*value = elem.String().c_str();
--
1.7.5.320.g20a15


More information about the iwhd-devel mailing list