M src/sc-argparse.c => src/sc-argparse.c +17 -4
@@ 17,6 17,7 @@ enum error {
LONG_FLAG_NO_PARAM_HAS_PARAM,
LONG_FLAG_MISSING_VAL,
STOP_PROCESSING,
+ MALFORMED_INTEGER,
};
#define error(err, state) \
@@ 87,8 88,14 @@ static enum error sc_process_short_flag(struct state *state, int i)
arg_struct->val_string = state->argv[state->argidx];
} else {
/* SC_ARG_TYPE_INT */
+ char *out;
+ long int val;
state->argidx++;
- arg_struct->val_int = atoi(state->argv[state->argidx]);
+ arg = state->argv[state->argidx];
+ val = strtol(arg, &out, 10);
+ if (*arg == '\0' || *out != '\0')
+ error(MALFORMED_INTEGER, state);
+ arg_struct->val_int = (int)val;
}
return NO_ERROR;
}
@@ 128,10 135,16 @@ static enum error sc_process_long_flag(struct state *state)
value = state->argv[++state->argidx];
}
- if (arg_struct->type == SC_ARG_TYPE_STRING)
+ if (arg_struct->type == SC_ARG_TYPE_STRING) {
arg_struct->val_string = value;
- else
- arg_struct->val_int = atoi(value);
+ } else {
+ char *out;
+ long int val_int;
+ val_int = strtol(value, &out, 10);
+ if (*value == '\0' || *out != '\0')
+ error(MALFORMED_INTEGER, state);
+ arg_struct->val_int = (int)val_int;
+ }
return NO_ERROR;
}
M tests/main.c => tests/main.c +15 -1
@@ 74,7 74,7 @@ void test_intargs(void)
TEST_ASSERT_FALSE(argspec[0].seen);
reset_args(argspec);
- argspec[1].val_int = 5; /* need to reset default */
+ argspec[0].val_int = 5; /* need to reset default */
testarg = (char *[]){ "-b", "-500", "-c", "1234" };
sc_argparse(argspec, 4, testarg);
@@ 82,6 82,20 @@ void test_intargs(void)
TEST_ASSERT_EQUAL(-500, argspec[1].val_int);
TEST_ASSERT_TRUE(argspec[0].seen);
TEST_ASSERT_TRUE(argspec[1].seen);
+
+ reset_args(argspec);
+ argspec[0].val_int = 5; /* need to reset default */
+
+ testarg = (char *[]){ "-c", "not an int" };
+ TEST_ASSERT_LESS_THAN_INT(0, sc_argparse(argspec, 4, testarg));
+ TEST_ASSERT_EQUAL(argspec[0].val_int, 5);
+
+ reset_args(argspec);
+ argspec[0].val_int = 5; /* need to reset default */
+
+ testarg = (char *[]){ "--argb", "not an int" };
+ TEST_ASSERT_LESS_THAN_INT(0, sc_argparse(argspec, 4, testarg));
+ TEST_ASSERT_EQUAL(argspec[0].val_int, 5);
}
int main(void)