From 3366d1e79773c39ff74d98373508c71c0e0e84eb Mon Sep 17 00:00:00 2001 From: Marcin Wojdyr Date: Mon, 3 Feb 2020 20:17:03 +0100 Subject: [PATCH] stb_sprintf: avoid left shift of negative value fix undefined behaviour reported by UBSan: runtime error: left shift of negative value -9223372036854775808 and add a test case. fixes #800 --- stb_sprintf.h | 2 +- tests/test_sprintf.c | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/stb_sprintf.h b/stb_sprintf.h index 630d851..24d3707 100644 --- a/stb_sprintf.h +++ b/stb_sprintf.h @@ -1696,7 +1696,7 @@ static stbsp__int32 stbsp__real_to_str(char const **start, stbsp__uint32 *len, c if (expo == 0) // is zero or denormal { - if ((bits << 1) == 0) // do zero + if (((stbsp__uint64) bits << 1) == 0) // do zero { *decimal_pos = 1; *start = out; diff --git a/tests/test_sprintf.c b/tests/test_sprintf.c index 674e2c7..207a56a 100644 --- a/tests/test_sprintf.c +++ b/tests/test_sprintf.c @@ -85,6 +85,7 @@ int main() CHECK2("0.00", "%.2f", 1e-4); CHECK2("-5.20", "%+4.2f", -5.2); CHECK2("0.0 ", "%-10.1f", 0.); + CHECK2("-0.000000", "%f", -0.); CHECK2("0.000001", "%f", 9.09834e-07); #if USE_STB // rounding differences CHECK2("38685626227668133600000000.0", "%.1f", pow_2_85);