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 5 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
 	int diff;
173
 	int diff;
174
 
174
 
175
 	for ( ; max-- ; first_bytes++, second_bytes++ ) {
175
 	for ( ; max-- ; first_bytes++, second_bytes++ ) {
176
-		diff = ( *second_bytes - *first_bytes );
176
+		diff = ( *first_bytes - *second_bytes );
177
 		if ( diff )
177
 		if ( diff )
178
 			return diff;
178
 			return diff;
179
 		if ( ! *first_bytes )
179
 		if ( ! *first_bytes )
195
 	int diff;
195
 	int diff;
196
 
196
 
197
 	for ( ; ; first_bytes++, second_bytes++ ) {
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
 		if ( diff )
200
 		if ( diff )
201
 			return diff;
201
 			return diff;
202
 		if ( ! *first_bytes )
202
 		if ( ! *first_bytes )

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

88
 	ok ( strcmp ( "Hello", "hello" ) != 0 );
88
 	ok ( strcmp ( "Hello", "hello" ) != 0 );
89
 	ok ( strcmp ( "Hello", "Hello world!" ) != 0 );
89
 	ok ( strcmp ( "Hello", "Hello world!" ) != 0 );
90
 	ok ( strcmp ( "Hello world!", "Hello" ) != 0 );
90
 	ok ( strcmp ( "Hello world!", "Hello" ) != 0 );
91
+	ok ( strcmp ( "abc", "def" ) < 0 );
91
 
92
 
92
 	/* Test strncmp() */
93
 	/* Test strncmp() */
93
 	ok ( strncmp ( "", "", 0 ) == 0 );
94
 	ok ( strncmp ( "", "", 0 ) == 0 );

Loading…
Cancel
Save