Browse Source

[libc] Fix strcmp()/strncmp() to return proper values

Fix strcmp() and strncmp() to return proper standard positive/negative
values for unequal strings.  Current implementation is backwards
(i.e. the functions are returning negative when should be positive and
vice-versa).

Currently all consumers of these functions only check the return value
for ==0 or !=0 and so we can safely change the implementation without
breaking things.

Signed-off-by: Aaron Young <Aaron.Young@oracle.com>
Modified-by: Michael Brown <mcb30@ipxe.org>
Signed-off-by: Michael Brown <mcb30@ipxe.org>
tags/v1.20.1
Aaron Young 6 years ago
parent
commit
3946aa9bac
2 changed files with 4 additions and 3 deletions
  1. 3
    3
      src/core/string.c
  2. 1
    0
      src/tests/string_test.c

+ 3
- 3
src/core/string.c View File

@@ -173,7 +173,7 @@ int strncmp ( const char *first, const char *second, size_t max ) {
173 173
 	int diff;
174 174
 
175 175
 	for ( ; max-- ; first_bytes++, second_bytes++ ) {
176
-		diff = ( *second_bytes - *first_bytes );
176
+		diff = ( *first_bytes - *second_bytes );
177 177
 		if ( diff )
178 178
 			return diff;
179 179
 		if ( ! *first_bytes )
@@ -195,8 +195,8 @@ int strcasecmp ( const char *first, const char *second ) {
195 195
 	int diff;
196 196
 
197 197
 	for ( ; ; first_bytes++, second_bytes++ ) {
198
-		diff = ( toupper ( *second_bytes ) -
199
-			 toupper ( *first_bytes ) );
198
+		diff = ( toupper ( *first_bytes ) -
199
+			 toupper ( *second_bytes ) );
200 200
 		if ( diff )
201 201
 			return diff;
202 202
 		if ( ! *first_bytes )

+ 1
- 0
src/tests/string_test.c View File

@@ -88,6 +88,7 @@ static void string_test_exec ( void ) {
88 88
 	ok ( strcmp ( "Hello", "hello" ) != 0 );
89 89
 	ok ( strcmp ( "Hello", "Hello world!" ) != 0 );
90 90
 	ok ( strcmp ( "Hello world!", "Hello" ) != 0 );
91
+	ok ( strcmp ( "abc", "def" ) < 0 );
91 92
 
92 93
 	/* Test strncmp() */
93 94
 	ok ( strncmp ( "", "", 0 ) == 0 );

Loading…
Cancel
Save