FormatBytes function bug fixes

- Use snprintf instead to avoid stack buffer overflow.
- Make sure nBytes has a value before using it to create an index for the suffix.
This commit is contained in:
Kawe Mazidjatari 2023-08-01 14:45:55 +02:00
parent 8e8b2ace38
commit a4da4afd19

View File

@ -991,11 +991,11 @@ string PrintPercentageEscape(const string& svInput)
// For formatting a STL string to a prettified representation of input bytes.
string FormatBytes(size_t nBytes)
{
char szBuf[128] = "";
char szBuf[128];
const char* szPrefix[] = { "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB" };
const int iBase = 1024;
size_t c = (std::min)((size_t)(log((double)nBytes) / log((double)iBase)), (size_t)sizeof(szPrefix) - 1);
sprintf(szBuf, "%1.2lf %s", nBytes / pow((double)iBase, c), szPrefix[c]);
size_t c = nBytes ? (std::min)((size_t)(log((double)nBytes) / log((double)iBase)), (size_t)sizeof(szPrefix) - 1) : 0;
snprintf(szBuf, sizeof(szBuf), "%1.2lf %s", nBytes / pow((double)iBase, c), szPrefix[c]);
return string(szBuf);
}