Sitelet https://web.archive.org/web/20220622104348/https://github.com/OpenRCT2/OpenRCT2/issues/17405
Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

String::Format_VA memory leaks #17405

Open
Broxzier opened this issue Jun 18, 2022 · 1 comment
Open

String::Format_VA memory leaks #17405

Broxzier opened this issue Jun 18, 2022 · 1 comment
Labels
bug good first issue refactor

Comments

@Broxzier
Copy link
Member

@Broxzier Broxzier commented Jun 18, 2022 •

Operating System

Windows 10, 64 bit

OpenRCT2 build

OpenRCT2, v0.4.0-174-gc8df66f (c8df66f on develop) provided by GitHub

Describe the issue

The implementation of String::Format_VA (mostly called from the String::Format overload without the buffer argument) allocates space for the string, and it's up to the user to free this (Memory::Free). This is however rarely done, instead it is mostly used as an argument for assignment to a std::string.

utf8* Format_VA(const utf8* format, va_list args)
{
va_list args1, args2;
va_copy(args1, args);
va_copy(args2, args);
// Try to format to a initial buffer, enlarge if not big enough
size_t bufferSize = 4096;
utf8* buffer = Memory::Allocate<utf8>(bufferSize);
// Start with initial buffer
int32_t len = vsnprintf(buffer, bufferSize, format, args);
if (len < 0)
{
Memory::Free(buffer);
va_end(args1);
va_end(args2);
// An error occurred...
return nullptr;
}
size_t requiredSize = static_cast<size_t>(len) + 1;
if (requiredSize > bufferSize)
{
// Try again with bigger buffer
buffer = Memory::Reallocate<utf8>(buffer, bufferSize);
len = vsnprintf(buffer, bufferSize, format, args);
if (len < 0)
{
Memory::Free(buffer);
va_end(args1);
va_end(args2);
// An error occurred...
return nullptr;
}
}
else
{
// Reduce buffer size to only what was required
bufferSize = requiredSize;
buffer = Memory::Reallocate<utf8>(buffer, bufferSize);
}
// Ensure buffer is terminated
buffer[bufferSize - 1] = '\0';
va_end(args1);
va_end(args2);
return buffer;
}

Since almost all cases use std::string already, the best approach would be to return a std::string or a u8string here.

Area(s) with issue?

Building the game

@Broxzier Broxzier added bug good first issue refactor labels Jun 18, 2022
@SaumyaBhushan
Copy link

@SaumyaBhushan SaumyaBhushan commented Jun 19, 2022

I would like to take this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug good first issue refactor
Projects
None yet
Development

No branches or pull requests

2 participants