Skip to content

Commit 6812bc4

Browse files
[libc] Fix off by one in long double buffer size (#80889)
The size for the long double BLOCK_BUFFER_LEN is calculated based on the properties of the long double type. Somewhere in the calculation, the result was mis-rounded so that the buffer was one element too small. This patch fixes the issue and adds asserts to catch it sooner in the future.
1 parent cdd9221 commit 6812bc4

File tree

1 file changed

+5
-1
lines changed

1 file changed

+5
-1
lines changed

libc/src/__support/float_to_string.h

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -651,7 +651,8 @@ template <> class FloatToString<long double> {
651651
int int_block_index = 0;
652652

653653
static constexpr size_t BLOCK_BUFFER_LEN =
654-
internal::div_ceil(internal::log10_pow2(FLOAT_AS_INT_WIDTH), BLOCK_SIZE);
654+
internal::div_ceil(internal::log10_pow2(FLOAT_AS_INT_WIDTH), BLOCK_SIZE) +
655+
1;
655656
BlockInt block_buffer[BLOCK_BUFFER_LEN] = {0};
656657
size_t block_buffer_valid = 0;
657658

@@ -693,6 +694,7 @@ template <> class FloatToString<long double> {
693694
int_block_index = 0;
694695

695696
while (float_as_int > 0) {
697+
LIBC_ASSERT(int_block_index < static_cast<int>(BLOCK_BUFFER_LEN));
696698
block_buffer[int_block_index] = grab_digits(float_as_int);
697699
++int_block_index;
698700
}
@@ -785,6 +787,8 @@ template <> class FloatToString<long double> {
785787
if (block_index > static_cast<int>(block_buffer_valid) || block_index < 0)
786788
return 0;
787789

790+
LIBC_ASSERT(block_index < static_cast<int>(BLOCK_BUFFER_LEN));
791+
788792
return block_buffer[block_index];
789793
}
790794

0 commit comments

Comments
 (0)