Skip to content

Commit

Permalink
Fix an issue where util_sscanf_int("") parsed as 0
Browse files Browse the repository at this point in the history
  • Loading branch information
eivindjahren committed Aug 7, 2024
1 parent b1121a9 commit 7ad751f
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 11 deletions.
6 changes: 6 additions & 0 deletions lib/util/tests/ert_util_sscan_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,12 @@ void test_sscanf_int() {
test_assert_false(util_sscanf_int("7.5", &value));
test_assert_int_equal(value, 1);

test_assert_false(util_sscanf_int("abc1", &value));
test_assert_int_equal(value, 1);

test_assert_false(util_sscanf_int("", &value));
test_assert_int_equal(value, 1);

// max and min
char buffer[30];
snprintf(buffer, 30, "-%d", INT_MAX);
Expand Down
20 changes: 9 additions & 11 deletions lib/util/util.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1207,29 +1207,27 @@ bool util_sscanf_octal_int(const char *buffer, int *value) {
true if the parsing succeeded, and false otherwise. If parsing
succeeded, the integer value is returned by reference.
*/

bool util_sscanf_int(const char *buffer, int *value) {
if (!buffer)
return false;

bool value_OK = false;
char *error_ptr;

int tmp_value = strtol(buffer, &error_ptr, 10);

/*
Skip trailing white-space
*/
if (error_ptr == buffer)
return false;

// Skip trailing white-space
while (error_ptr[0] != '\0' && isspace(error_ptr[0]))
error_ptr++;

if (error_ptr[0] == '\0') {
value_OK = true;
if (value != NULL)
*value = tmp_value;
}
return value_OK;
if (error_ptr[0] != '\0')
return false;

if (value != NULL)
*value = tmp_value;
return true;
}

/*
Expand Down

0 comments on commit 7ad751f

Please sign in to comment.