Fix for remainder overflow, when in rare cases adding remainder to divider exceeded 1 and turned the total to 1000 in final formatting, taking up the space for the unit character.
Issue was caused by the way the final value was calculated in snprintf call, where remainder and divisor/2 was added back to the divided number. If remainder + divisor/2 was larger than 1024, it added 1 to the final value. If the final value as already 999 (as in the example reported), that brought it to 1000. If the buffer length provided was 4+1 (as is the case with ls), that left no space for the unit character.
Same issue was also present for other numbers if too small buffer lengths where used.
The fix continues the division of the original number if the above case happens -- added the appropriate check to the for loop performing the division. This lowers the value shown, to make it fit into the buffer space provided (1.0M for 4+1 character buffer, as used by ls).
Add test case for the reported bug and extend test program to support providing buffer length (ls -lh uses 5, tests hard-coded 4).
Reported by: Masachika ISHIZUKA <ish@amail.plala.or.jp>
Submitted by: Pawel Biernacki <pawel.biernacki@gmail.com>
Sponsored by: Mysterious Code Ltd.
PR: 224498
MFC: 1 week