CStdString
CStdString copied to clipboard
Memory leak in Format(...) function
If the formatted string is bigger than 512 characters, the Format(...) routine will leak memory on Windows Unicode builds. This is, because pBuf is not freed from the previous iteration in the following loop:
void FormatV(const CT* szFormat, va_list argList)
(...)
do
{
// Grow more than linearly (e.g. 512, 1536, 3072, etc)
nChars += ((nTry+1) * FMT_BLOCK_SIZE);
//!!alloca is unavailable/problematic in many environments:
//!! pBuf = reinterpret_cast<CT*>(_alloca(sizeof(CT)*nChars));
/***** This free() is missing *********/
if (pBuf) free(pBuf);
pBuf = reinterpret_cast<CT*>(malloc(sizeof(CT)*nChars));
if (!pBuf) throw(std::bad_alloc());
nUsed = ssvsprintf(pBuf, nChars-1, szFormat, argList);
// Ensure proper NULL termination.
nActual = nUsed == -1 ? nChars-1 : SSMIN(nUsed, nChars-1);
pBuf[nActual]= '\0';
} while ( nUsed < 0 && nTry++ < MAX_FMT_TRIES );
While _alloca
isn't portable it does not suffer from unreleased memory. The memory will be freed automatically at the end of the function.
While
_alloca
isn't portable it does not suffer from unreleased memory. The memory will be freed automatically at the end of the function.
Yeah, however the actual implementation in this repo uses malloc, which implies the memory leak. We fixed this locally and as a good citizen, I just want to inform others, so that they do not stumble over this issue. Would have posted a pull request, however this repo seams unfortunately dead to me.
Sorry, I didn't recognized the comment around _alloca
is from this repos version of CStdString but thought it was from your implementation.
In this case you're obviously right about the memory leak.