From 6552f55f78145c603da8c08e867606a83f433616 Mon Sep 17 00:00:00 2001 From: Daniel Mendler Date: Mon, 20 May 2019 08:38:25 +0200 Subject: [PATCH] handle EOF condition in mp_fread, fix #163 --- bn_mp_fread.c | 25 ++++++++++++++----------- tommath_class.h | 2 +- 2 files changed, 15 insertions(+), 12 deletions(-) diff --git a/bn_mp_fread.c b/bn_mp_fread.c index bbb59a5a2..04a13168d 100644 --- a/bn_mp_fread.c +++ b/bn_mp_fread.c @@ -9,14 +9,9 @@ mp_err mp_fread(mp_int *a, int radix, FILE *stream) { mp_err err; mp_sign neg; - int ch, y; - unsigned pos; - - /* clear a */ - mp_zero(a); /* if first digit is - then set negative */ - ch = fgetc(stream); + int ch = fgetc(stream); if (ch == (int)'-') { neg = MP_NEG; ch = fgetc(stream); @@ -24,8 +19,17 @@ mp_err mp_fread(mp_int *a, int radix, FILE *stream) neg = MP_ZPOS; } - for (;;) { - pos = (unsigned)(ch - (int)'('); + /* no digits, return error */ + if (ch == EOF) { + return MP_ERR; + } + + /* clear a */ + mp_zero(a); + + do { + int y; + unsigned pos = (unsigned)(ch - (int)'('); if (mp_s_rmap_reverse_sz < pos) { break; } @@ -43,10 +47,9 @@ mp_err mp_fread(mp_int *a, int radix, FILE *stream) if ((err = mp_add_d(a, (mp_digit)y, a)) != MP_OKAY) { return err; } + } while ((ch = fgetc(stream)) != EOF); - ch = fgetc(stream); - } - if (mp_cmp_d(a, 0uL) != MP_EQ) { + if (!mp_iszero(a)) { a->sign = neg; } diff --git a/tommath_class.h b/tommath_class.h index f102f1c51..d51c7f8b7 100644 --- a/tommath_class.h +++ b/tommath_class.h @@ -398,7 +398,7 @@ # define BN_MP_ZERO_C # define BN_MP_MUL_D_C # define BN_MP_ADD_D_C -# define BN_MP_CMP_D_C +# define BN_MP_ISZERO_C #endif #if defined(BN_MP_FWRITE_C)