Add error handling for read_number and fix it

This commit is contained in:
olemorud
2023-04-25 07:22:07 +02:00
parent 08de9dc48b
commit 05e78fa523
3 changed files with 15 additions and 5 deletions

View File

@@ -12,11 +12,11 @@ CC := gcc
# -fsanitize={address,undefined} # -fsanitize={address,undefined}
CFLAGS.gcc.debug := -Og -ggdb -fanalyzer -DBACKTRACE -rdynamic -fsanitize=address -fno-omit-frame-pointer CFLAGS.gcc.debug := -Og -ggdb -fanalyzer -DBACKTRACE -rdynamic -fsanitize=address -fno-omit-frame-pointer
CFLAGS.gcc.release := -O3 -g -march=native -DNDEBUG CFLAGS.gcc.release := -O3 -g -march=native -DNDEBUG
CFLAGS.gcc := ${CFLAGS.gcc.${BUILD}} -Iinclude -Wall -Wextra -Wpedantic -Werror -fstack-protector-all -std=gnu11 CFLAGS.gcc := ${CFLAGS.gcc.${BUILD}} -Iinclude -Wall -Wextra -Wpedantic -Werror -Wno-strict-aliasing -fstack-protector-all -std=gnu11
CFLAGS.clang.debug=-O0 -g3 -DBACKTRACE -rdynamic CFLAGS.clang.debug=-O0 -g3 -DBACKTRACE -rdynamic
CFLAGS.clang.release=-O3 -g -march=native -DNDEBUG CFLAGS.clang.release=-O3 -g -march=native -DNDEBUG
CFLAGS.clang=-Wextra -Wall -Wpedantic -Werror -fstack-protector-all ${CFLAGS.clang.${BUILD}} CFLAGS.clang=-Iinclude -Wall -Wextra -Wpedantic -Werror -Wno-strict-aliasing -fstack-protector-all ${CFLAGS.clang.${BUILD}}
CFLAGS := ${CFLAGS.${COMPILER}} CFLAGS := ${CFLAGS.${COMPILER}}

View File

@@ -36,7 +36,7 @@ int main(int argc, char* argv[])
struct json_value x = parse_json_value(fp); struct json_value x = parse_json_value(fp);
print_json(x, 1); // print_json(x, 1);
json_value_delete(x); json_value_delete(x);

View File

@@ -106,6 +106,7 @@ struct json_value parse_json_value(FILE* fp)
default: default:
if (isdigit(c)) { if (isdigit(c)) {
ungetc(c, fp);
result.type = number; result.type = number;
result.number = read_number(fp); result.number = read_number(fp);
} else { } else {
@@ -364,9 +365,18 @@ bool read_boolean(FILE* fp)
*/ */
double read_number(FILE* fp) double read_number(FILE* fp)
{ {
double n; static const unsigned long neg_nan = 0xFFFFFFFFFFFFFFFFULL;
double n = *(double*)&neg_nan;
fscanf(fp, "%lf", &n); int n_read = fscanf(fp, "%lf", &n);
/* try to read as long instead */
if (n_read == 0) {
err_ctx(UNEXPECTED_CHAR, fp, "(%s) number expected, found %lf", __func__, n);
}
if (n_read == EOF)
err_ctx(EARLY_EOF, fp, "(%s) unexpected EOF", __func__);
return n; return n;
} }